What is wrong with my code? Null pointer exception

What is wrong with the code below? It will throw a NullPointerException at runtime.

public class Test { public String method1() { return null; } public Integer method2() { return null; } public static void main(String args[])throws Exception { Test m1 = new Test(); Integer v1 = (m1.method1() == null) ? m1.method2() : Integer.parseInt(m1.method1()); } } 
+4
source share
2 answers

Type a ? b : c a ? b : c is the type of the last value c . In this case, it is a int . This means that even when b selected, it is unpacked and then placed again in Integer. Since the value is null, this fails.

Here is an example that might help (or be more confusing)

 Integer i = 1000; // same as Integer j = Integer.valueOf(i == 1000 ? i.intValue() : 1000); Integer j = i == 1000 ? i : 1000; System.out.println(i == j); Integer k = i == 1000 ? i : (Integer) 1000; System.out.println(i == k); 

prints

 false true 

The reason the first result is false is because the expression is of type int (last argument), which means that i unpacked as int and reinstalled, so it can be assigned to Integer. This leads to another object (there are command line arguments that increase the size of the cache and change this value). In the second example, the type is Integer , so it is not unpacked and the object is the same.

+9
source

parseInt returns int. The compiler for unbox m1.method2 () does this, but it is null, so it throws:

 Integer v1 = (m1.method1() == null) ? m1.method2() : (Integer)Integer.parseInt(m1.method1()); 
+1
source

All Articles