开发者

Why do I get null pointer exception in this code?

开发者 https://www.devze.com 2023-01-19 00:16 出处:网络
public class Test { Integer i; int j; public static void main ( String [] args ) { Test t = new Test (); t.go();
public class Test {

    Integer i;
    int j;

    public static void main ( String [] args ) {
       Test t = new Test ();
       t.go();
    }

    public void go() {
       j=i;
       System.out.println(j);
       System.out.println(i开发者_StackOverflow社区);
    }
}

Output : Exception in thread "main" java.lang.NullPointerException at Test.go(Test.java:12) at Test.main(Test.java:8)


That's obviously not the error. You will get a runtime NullPointerException because you're unboxing a null reference (i) into a primitive (j). See JLS §5.1.8.

The reason i is null is that instance fields are initialized to 0, null, or false by default.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号