Pages

Tuesday, 10 May 2016

NPE while assign the Null value to primitive at runtime

public class TestOutput {

     public static void main(String[] args) {
           int value = solution();
           System.out.println(value);
     }

     private static int solution() {
           return true?0:null;
     }
}

Output: 0

When we assign the null value to primitive at runtime, it will throw NullPointerException.


public classTestOutput {

     public static voidmain(String[] args) {
           int value = solution();
           System.out.println(value);
     }

     private static intsolution() {
           return true?null:0;
     }
}
Output:
Exception in thread "main" java.lang.NullPointerException at TestOutput.solution(TestOutput.java:10) at TestOutput.main(TestOutput.java:5)

No comments:

Post a Comment