简体   繁体   中英

Why is this code not throwing a nullPointerException?

The code snippets are below.

I understand that the default value for a String is null and this is assigned to str . What I don't understand is why null is printed in this first case but not in other cases (like the second code snippet).

public class Case1{

    static String str;

    public static void main(String[] args){

        System.out.println(str);
    }
}

\\Code prints 'null' without quotes
public class Case2{

    public static void main(String[] args){

        String a[][] = { {}, null };
        System.out.println(a[1][0]);
    }
}

\\Code throws nullPointerException

Any explanation would be greatly appreciated.

In your second example what you are doing is to access the first value of an nonexistent array:

String a[][] = { {}, null };

So a[1] is the null value, and there is no [0] of that null.

In your example you are trying to access value on the null.

Look at the following code

 String a[][] = { {}, null };
 System.out.println(a[1]);

it will print

null

and when you try to access the 0th element on the null, it throw nullpointer expections because you are try to access a element on null

String a[][] = { {}, null };
System.out.println(a[1][0]);

it will output

Exception in thread "main" java.lang.NullPointerException

In case1, You are just printing string and no value is assigned there, So by default null is printed. You do not perform any operation with that string to throw NullPointerException there. Hence It doesn't throw any exceptions.

In case2, You assign null value to string Array and tries to get with index so with null object. Hence you got nullPointerException.

if you change case2 with following code you will get null there too.

public class Case2{

public static void main(String[] args){

    String a[][] = new String[2][2];
    a[1][0] = null;
    System.out.println(a[1][0]);
    }
}

\Code prints 'null' without quotes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM