nullpointerexception - Tricky ternary operator in Java - autoboxing -


let's @ simple java code in following snippet:

public class main {      private int temp() {         return true ? null : 0;         // no compiler error - compiler allows return value of null         // in method signature returns int.     }      private int same() {         if (true) {             return null;             // same not possible if,             // , causes compile-time error - incompatible types.         } else {             return 0;         }     }      public static void main(string[] args) {         main m = new main();         system.out.println(m.temp());         system.out.println(m.same());     } } 

in simplest of java code, temp() method issues no compiler error though return type of function int, , trying return value null (through statement return true ? null : 0;). when compiled, causes run time exception nullpointerexception.

however, appears same thing wrong if represent ternary operator if statement (as in same() method), does issue compile-time error! why?

the compiler interprets null null reference integer, applies autoboxing/unboxing rules conditional operator (as described in java language specification, 15.25), , moves happily on. generate nullpointerexception @ run time, can confirm trying it.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -