3

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!

m0therway
  • 411
  • 1
  • 4
  • 12
  • You set `arr` to `null`. What else could possibly happen when you try to access an element of `arr`? – NullUserException Nov 11 '11 at 04:51
  • 2
    Should I downvote this question? >:) – Hendra Jaya Nov 11 '11 at 05:06
  • `arr` is a `String[]` variable. If you set `arr` to null then you are setting the `String[]` to null -- the initial `new String[10]` is gone. Then setting `arr[0]` tries to use a null array reference. You could set `arr[0]` to be null and then set it to be `"one"` but not the `arr` array. – Gray Nov 11 '11 at 05:14
  • Think of it as null[0] = "one". `arr` is no longer referencing ("pointing at", sort of) the space that could hold up to ten `String`s. – Dave Newton Nov 11 '11 at 05:19

3 Answers3

15

Because you made arr referring to null, so it threw a NullPointerException.


EDIT:

Let me explain it via figures:

After this line:

String arr[] = new String[10];

10 places will be reserved in the heap for the array arr:

enter image description here

and after this line:

arr = null;

You are removing the reference to the array and make it refer to null:

enter image description here

So when you call this line:

arr[0] = "one";

A NullPointerException will be thrown.

Eng.Fouad
  • 107,075
  • 62
  • 298
  • 390
1

With arr = null; you are deleting the reference to the object. So you can't access it anymore with arr[anynumber] .

0

arr is null, and then... if it did print one, wouldn't you be surprised? put a string into a null?

James.Xu
  • 8,023
  • 5
  • 23
  • 35
  • arr[0] is not null. I'm printing arr[0]. Why do you think arr[0] is null? – m0therway Nov 11 '11 at 04:55
  • arr is null, your exception is thrown from `arr[0] = "one";` **NOT** `System.out.print(arr[0]);` you can not put something into a `null`. – James.Xu Nov 11 '11 at 04:56