2

Can somebody explain why the getY() method causing NullPointerException.

public class NullTest {
    private String s = "";

    public Long getValue() {
        return null;
    }

    public Long getX() {
        return s != null ? getValue() : new Long(0);
    }

    public Long getY() {
        return s != null ? getValue() : 0L;
    }

    public static void main(String[] args) {
        NullTest nt = new NullTest();
        System.out.println("x = " + nt.getX());
        System.out.println("y = " + nt.getY());
    }
}

Sample output:

x = null
Exception in thread "main" java.lang.NullPointerException
    at NullTest.getY(NullTest.java:13)
    at NullTest.main(NullTest.java:19)

1 Answers1

2

The type of the expression s != null ? getValue() : 0L is long, not Long. Therefore, if s != null is true and getValue() is null, a NullPointerExcetpion is thrown when trying to unbox that null to long.

You don't get this issue in getX(), since in the expression s != null ? getValue() : new Long(0), both getValue() and new Long(0) are Long, so the type of the expression is Long, and no unboxing takes place.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • If I replace getValue() with null in getY() no exception is thrown. Type of expression is long for this case but no exception is thrown. return s != null ? null : 0L; – Muhammad Towfique Imam Mar 11 '19 at 13:18
  • @MuhammadTowfiqueImam there are different rules when one of the operands is `null`. You can see tables that summarize the rules here: https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25 – Eran Mar 11 '19 at 13:26