Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with my code? NullPointerException

What is wrong with the below code? It will throw NullPointerException while execution time.

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());
  }
}
like image 457
sprabhakaran Avatar asked Dec 27 '22 10:12

sprabhakaran


1 Answers

The type of a a ? b : c is the type of the last value c. In this case it's an int. This means that even though b is being chosen it is being unboxed and then re-boxed into an Integer. As the value is null, this fails.

Here is a similar example which may 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 that expression has a type of int (the last argument) which means i is unboxed to be an int and reboxed so it can be assigned to the Integer. This results in a different object (There are command line args which would increase the cache size and change this) In the second example the type is Integer so it is not unboxed and the object is the same.

like image 79
Peter Lawrey Avatar answered Jan 14 '23 14:01

Peter Lawrey