Can someone tell me what’s wrong with this Java code?
This array is : static String [][] data = new String[6][2]; But in this case, data[0][1]="abcd" and data[1][1]="efgh", the remaining data[2-5][1] should be null. I am just trying to print out the non-null ones. At (j=2,k=3), the code doesn’t get executed after that. For eg, the “I am here3” doesn’t get printed.
int k=1;
System.out.println("data[2][0]="+data[2][0]);
for(int j=0; j<data.length; j++,k++) {
System.out.println("j="+j+" k="+k);
if (!(data[j][0].equals("null"))) {
System.out.println("I am here2");
sbissues = sbissues.append("\n");
sbissues = sbissues.append(k);
sbissues = sbissues.append(". ");
sbissues = sbissues.append(data[j][1]);
}
System.out.println("sbissues="+sbissues.toString());
System.out.println("I am here1");
}
System.out.println("I am here3");
The output looks like:
data[2][0]=null
j=0 k=1
I am here2
sbissues=
1. abcd
I am here1
j=1 k=2
I am here2
sbissues=
1. abcd
2. efgh
I am here1
j=2 k=3
The problem is that i never reach the “I am here3”.
Thanks guys for the answers, they are all correct (to use !=null instead of .equals). I guess i can’t vote for all of you, i’m just allowed to vote once.
My guess is you don’t want it printing anything when it’s null.
Use this for your if statement instead:
In java complex variables are references to objects. You can have two variables pointing to the same object. When a variable is pointing to nothing then it’s null. You cannot dereference a null variable, that’s when you get a NullPointerException.
The primitive data types like int, long, byte, etc. behave differently. Every time you assign you’re making a copy of the data. They cannot be null.