Returning null as primitive type in Java works. Why?

Viewed 608

why does javac for:

int xx() {
      return true ? null : 0;   
}

returns?

int xx();
   0: aconst_null
   1: checkcast     #2   // java/lang/Integer
   4: invokevirtual #3   // java/lang/Integer.intValue:()I
   7: ireturn

Note that my xx returns int- a primitive type. Why is javac disobedient and tries to return reference type - Integer (java.lang.Integer.intValue())

2 Answers

Java has the feature that instances of java.lang.Integer are automatically unboxed (by inserting a Integer.intValue() call).

If you try to return null in your method, the compiler thinks that you have a instance of java.lang.Integer. This java.lang.Integer is then unboxed and returned.

It happens because of a feature called Autoboxing.

You are trying to return null - a primitive int can not have a value of null, but the class Integer, can. Java automatically boxes and unboxes between the primitives (int,char,bool and so on) and their classes (Integer,Character,Boolean) without your intervention, to accommodate reference type behavior .

Related