Why does autoboxing in Java allow me to have 3 possible values for a boolean?

后端 未结 9 662
你的背包
你的背包 2020-12-06 07:43

Reference: http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html

\"If your program tries to autounbox null, it will throw a NullPointerEx

9条回答
  •  执笔经年
    2020-12-06 07:55

    Boxed types are reference types, and all reference types, primitive boxes or not, can refer to null. That's why a Boolean can refer to null. So can an Integer. So can a String, etc.

    Boxed types are not designed to make Java truly object oriented. Java will never be a purely object oriented language, and you should not code as if this is the case. Primitive types will never go away, and in fact should be preferred whenever there's a choice.

    Here's a quote from Effective Java 2nd Edition, Item 49: Prefer primitive types to boxed primitives (emphasis by author):

    In summary, use primitives in preference to boxed primitive whenever you have the choice. Primitive types are simpler and faster. If you must use boxed primitives, be careful! Autoboxing reduces the verbosity, but not the danger, of using boxed primitives. When your program compares two boxed primitives with the == operator, it does an identity comparison, which is almost certainly not what you want. When your program does mixed-type computations involving boxed and unboxed primitives, it does unboxing, and when your program does unboxing, it can throw NullPointerException. Finally, when your program boxes primitive values, it can result in costly and unnecessary object creations.

提交回复
热议问题