Seem like you required dynamic list, so what you need is replace String[] data = null; to use List
List data = new ArrayList<String>();
String[] data2 = null;
String[] datas = res.split("(s1)");
int i1 = 0;
int i2 = 0;
for (String datasx : datas) {
i1++;
String[] datas2 = datasx.split("(s2)");
for (String datas2x : datas2) {
String[] odcinek = datas2x.split("(s3)");
data.add(odcinek[1] + "////" + odcinek[2] + "////" + odcinek[6]);
i2++;
}
}
Answer from Pau Kiat Wee on Stack OverflowSeem like you required dynamic list, so what you need is replace String[] data = null; to use List
List data = new ArrayList<String>();
String[] data2 = null;
String[] datas = res.split("(s1)");
int i1 = 0;
int i2 = 0;
for (String datasx : datas) {
i1++;
String[] datas2 = datasx.split("(s2)");
for (String datas2x : datas2) {
String[] odcinek = datas2x.split("(s3)");
data.add(odcinek[1] + "////" + odcinek[2] + "////" + odcinek[6]);
i2++;
}
}
You are initializing the array data to be null, when you try to access it it gives you null pointer access error.
You must initialize it to the appropriate type before you try to acces it i.e. initialize it to String[] instead of null.
eclipse - 'Null pointer access' when using java output parameters - Stack Overflow
java - Potential null pointer access - Stack Overflow
Improper warning - Potential null pointer access
exception - How to suppress null pointer access warning in java? - Stack Overflow
This is described in Eclipse bug 260293 one of several duplicates closed as Won't Fix.
The bug basically says that Eclipse does not track the correlation between the variables isNotNull and nullableString so it doesn't know that the value can't be null.
use conditional operator while assigning the boolean varaible isNotNull. change the line
boolean isNotNull = nullableString != null;
to
boolean isNotNull = (if(nullableString != null)?True:False);
Since there is no concept of out parameters in java ...
The reference obj is a copy of the reference objA, so assigning a new object to obj will not change objA. This means that using obj as an out parameter is not supported by java.
Because of this a java method can return only one value. The following are possible solutions/workarounds.
Solution 1: exception instead of boolean (only if boolean indicates an error)
ClassA objA = null;
try{
objA = myMethod();
//DO something with objA
}catch(MyException ex){
}
Solution 2: return null in case of an error.
ClassA objA = null;
objA = myMethod();
if(objA != null)
{ //DO something with objA
}
Solution 3: use a Pair to return several values
MyPair mp = myMethod();
if(mp.first){
}
MyPair myMethod(){
MyPair ret = new MyPair();
mp.first = ...;//boolean
mp.second = new ClassA();
return ret;
}
class MyPair {
boolean first;
ClassA second;
}
Soultion 4: use single element arrays - ugly only use in extreme cases
ClassA[] objA = new ClassA[1];
if(myMethod(objA))
{
}
boolean myMethod(ClassA[] obj){
obj[0] = new ClassA();
}
You can't really do what you're trying to do in java since, as you say, java doesn't support output parameters.
Method parameters are local variables, so making assignments to them has no effect outside the scope of the method. In other words, this:
public void foo(Object obj) {
obj = new Object();
}
Is effectively equivalent (from the point of view of the code calling foo(Object)) as this:
public void foo() {
Object obj = new Object();
}
Pointless, since the created object will be thrown out once foo() returns.
Probably, what you want to do is change your method to return the object your method creates:
public ClassA myMethod() {
ClassA obj = ....
...
return obj;
}
Then in your calling code:
ClassA objA = myMethod();
if (objA != null) {
...
}
Alternatively, you could instantiate the instance of ClassA outside your method and pass that value is, and have the method modify it in some way:
public boolean myMethod(ClassA obj) {
obj.setValue(...);
return true;
}
...
ClassA objA = new ClassA();
if (myMethod(objA) {
Object val = objA.getValue();
...
}
Without knowing more about your specific problem, it's hard to say which design is better.
UPDATE:
The multi-parameter example you added is flat-out impossible in java, unfortunately. Everyone says java is pass-by-reference, but in reality it's more like pass-by-reference-value. A method can modify objects passed to it, but it cannot modify what the variables in the calling scope refer to. If you come from a C++ background, object references in java are more like pointers (without the pointer arithmetic) than they are like C++ references.
To make this more concrete, consider the following class:
public class ParameterPassing {
public static void setParams(Integer value1, Integer value2) {
System.out.println("value1 before: " + value1);
System.out.println("value2 before: " + value2);
value1 = new Integer(1);
value2 = new Integer(2);
System.out.println("value1 after: " + value1);
System.out.println("value2 after: " + value2);
}
public static void main(String[] args) {
Integer valNull = null;
Integer val0 = new Integer(0);
System.out.println("valNull before: " + valNull);
System.out.println("val0 before: " + val0);
setParams(valNull, val0);
System.out.println("valNull after: " + valNull);
System.out.println("val0 after: " + val0);
}
}
When you run this, you'll get this output:
valNull before: null
val0 before: 0
value1 before: null
value2 before: 0
value1 after: 1
value2 after: 2
valNull after: null
val0 after: 0
As you can see, the assignments inside the setParams() method have no effect on what valNull and val0 refer to.
If you really need multiple "output" parameters for a single method, you're going to have to wrap them in some other object, or rethink your design. Perhaps you could make the references member variables rather than locals and have your method modify them directly:
public class MyClass {
private ClassA objA;
private ClassB objB;
...
private boolean initObjects() {
objA = ...;
objB = ...;
return true;
}
public void otherMethod() {
...
if(initObjects() {
// Use objA, objB
}
}
}
Thanks to the comment by @Slaw for this answer -
I modified my code in the following way -
String name = null;
int length = 0;
boolean flag = false;
if(flag) {
name = "abcd";
}
try {
length = name.length();
System.out.println("Number of letters in name: " + length);
} catch(NullPointerException e) {
System.out.println("NullPointerException occured");
}
System.out.println("I am being executed");
Now I longer have the warning.
Here, as suggested by @Slaw I made sure that the variable name has a chance of not being null.
Add the following annotation to either the method or class to suppress warnings about potential NullPointerExceptions being thrown. This works in Intellij, although I am unsure about Eclipse.
@SuppressWarnings("DataFlowIssue")
You could stop using Eclipse.
Hey, it's a solution. It may not be the one you want, but it solves the problem and isn't really a bad solution.
More seriously, you could:
- adjust compiler warning settings,
- use
SuppressWarningsat method or class level, - use a more modern compiler (apparently later versions do not trigger this for simple cases),
- rewrite your code to work and assign the return value of
checkNotNulltoann.
Eclipse e4 has much better support for null checks and resource tracking in the compiler.
Another solution is writing your own version of checkNotNull like so:
@Nonnull
public static <T> T checkNotNull(@Nullable T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
Now you can use this approach:
SomeAnnotation ann = Preconditions.checkNotNull( type.getAnnotation( SomeAnnotation.class ) );
(I've omitted the version of checkNotNull() which take error messages; they work in the same way).
I'm wondering why Guava doesn't do that since they already use these annotation elsewhere.
There are two overarching types of variables in Java:
Primitives: variables that contain data. If you want to manipulate the data in a primitive variable you can manipulate that variable directly. By convention primitive types start with a lowercase letter. For example variables of type
intorcharare primitives.References: variables that contain the memory address of an
Objecti.e. variables that refer to anObject. If you want to manipulate theObjectthat a reference variable refers to you must dereference it. Dereferencing usually entails using.to access a method or field, or using[to index an array. By convention reference types are usually denoted with a type that starts in uppercase. For example variables of typeObjectare references.
Consider the following code where you declare a variable of primitive type int and don't initialize it:
int x;
int y = x + x;
These two lines will crash the program because no value is specified for x and we are trying to use x's value to specify y. All primitives have to be initialized to a usable value before they are manipulated.
Now here is where things get interesting. Reference variables can be set to null which means "I am referencing nothing". You can get a null value in a reference variable if you explicitly set it that way, or a reference variable is uninitialized and the compiler does not catch it (Java will automatically set the variable to null).
If a reference variable is set to null either explicitly by you or through Java automatically, and you attempt to dereference it you get a NullPointerException.
The NullPointerException (NPE) typically occurs when you declare a variable but did not create an object and assign it to the variable before trying to use the contents of the variable. So you have a reference to something that does not actually exist.
Take the following code:
Integer num;
num = new Integer(10);
The first line declares a variable named num, but it does not actually contain a reference value yet. Since you have not yet said what to point to, Java sets it to null.
In the second line, the new keyword is used to instantiate (or create) an object of type Integer, and the reference variable num is assigned to that Integer object.
If you attempt to dereference num before creating the object you get a NullPointerException. In the most trivial cases, the compiler will catch the problem and let you know that "num may not have been initialized," but sometimes you may write code that does not directly create the object.
For instance, you may have a method as follows:
public void doSomething(SomeObject obj) {
// Do something to obj, assumes obj is not null
obj.myMethod();
}
In which case, you are not creating the object obj, but rather assuming that it was created before the doSomething() method was called. Note, it is possible to call the method like this:
doSomething(null);
In which case, obj is null, and the statement obj.myMethod() will throw a NullPointerException.
If the method is intended to do something to the passed-in object as the above method does, it is appropriate to throw the NullPointerException because it's a programmer error and the programmer will need that information for debugging purposes.
In addition to NullPointerExceptions thrown as a result of the method's logic, you can also check the method arguments for null values and throw NPEs explicitly by adding something like the following near the beginning of a method:
// Throws an NPE with a custom error message if obj is null
Objects.requireNonNull(obj, "obj must not be null");
Note that it's helpful to say in your error message clearly which object cannot be null. The advantage of validating this is that 1) you can return your own clearer error messages and 2) for the rest of the method you know that unless obj is reassigned, it is not null and can be dereferenced safely.
Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething() could be written as:
/**
* @param obj An optional foo for ____. May be null, in which case
* the result will be ____.
*/
public void doSomething(SomeObject obj) {
if(obj == null) {
// Do something
} else {
// Do something else
}
}
Finally, How to pinpoint the exception & cause using Stack Trace
What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
Sonar with find bugs can detect NPE. Can sonar catch null pointer exceptions caused by JVM Dynamically
Now Java 14 has added a new language feature to show the root cause of NullPointerException. This language feature has been part of SAP commercial JVM since 2006.
In Java 14, the following is a sample NullPointerException Exception message:
in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.List.size()" because "list" is null
List of situations that cause a NullPointerException to occur
Here are all the situations in which a NullPointerException occurs, that are directly* mentioned by the Java Language Specification:
- Accessing (i.e. getting or setting) an instance field of a null reference. (static fields don't count!)
- Calling an instance method of a null reference. (static methods don't count!)
throw null;- Accessing elements of a null array.
- Synchronising on null -
synchronized (someNullReference) { ... } - Any integer/floating point operator can throw a
NullPointerExceptionif one of its operands is a boxed null reference - An unboxing conversion throws a
NullPointerExceptionif the boxed value is null. - Calling
superon a null reference throws aNullPointerException. If you are confused, this is talking about qualified superclass constructor invocations:
class Outer {
class Inner {}
}
class ChildOfInner extends Outer.Inner {
ChildOfInner(Outer o) {
o.super(); // if o is null, NPE gets thrown
}
}
Using a
for (element : iterable)loop to loop through a null collection/array.switch (foo) { ... }(whether its an expression or statement) can throw aNullPointerExceptionwhenfoois null.foo.new SomeInnerClass()throws aNullPointerExceptionwhenfoois null.Method references of the form
name1::name2orprimaryExpression::namethrows aNullPointerExceptionwhen evaluated whenname1orprimaryExpressionevaluates to null.a note from the JLS here says that,
someInstance.someStaticMethod()doesn't throw an NPE, becausesomeStaticMethodis static, butsomeInstance::someStaticMethodstill throw an NPE!
* Note that the JLS probably also says a lot about NPEs indirectly.
NullPointerExceptions are exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a NullPointerException. These are the most common, but other ways are listed on the NullPointerException javadoc page.
Probably the quickest example code I could come up with to illustrate a NullPointerException would be:
public class Example {
public static void main(String[] args) {
Object obj = null;
obj.hashCode();
}
}
On the first line inside main, I'm explicitly setting the Object reference obj equal to null. This means I have a reference, but it isn't pointing to any object. After that, I try to treat the reference as though it points to an object by calling a method on it. This results in a NullPointerException because there is no code to execute in the location that the reference is pointing.
(This is a technicality, but I think it bears mentioning: A reference that points to null isn't the same as a C pointer that points to an invalid memory location. A null pointer is literally not pointing anywhere, which is subtly different than pointing to a location that happens to be invalid.)
name != null || !name.isEmpty()
- If name is not null, the second condition is never checked;
- if name is null, the second condition is checked and throws a
NullPointerException.
When you do:
if(name!=null || !name.isEmpty())
Then if the second part is reached, name is null due to Short-circuit evaluation.
Remember that false && anything is false and true || anything is true.