This problem came up in a practice test: create a new string array, initialize it to null, then initializing the first element and printing it. Why does this result in a null pointer exception? Why doesn't it print "one"? Is it something to do with string immutability?
public static void main(String args[]) {
try {
String arr[] = new String[10];
arr = null;
arr[0] = "one";
System.out.print(arr[0]);
} catch(NullPointerException nex) {
System.out.print("null pointer exception");
} catch(Exception ex) {
System.out.print("exception");
}
}
Thanks!
arr
tonull
. What else could possibly happen when you try to access an element ofarr
? – NullUserException Nov 11 '11 at 4:51arr
is aString[]
variable. If you setarr
to null then you are setting theString[]
to null -- the initialnew String[10]
is gone. Then settingarr[0]
tries to use a null array reference. You could setarr[0]
to be null and then set it to be"one"
but not thearr
array. – Gray Nov 11 '11 at 5:14arr
is no longer referencing ("pointing at", sort of) the space that could hold up to tenString
s. – Dave Newton Nov 11 '11 at 5:19