Boolean instanceof Object is true?

£可爱£侵袭症+ 提交于 2019-12-12 14:03:45

问题


I've been learning Java in my spare time and have a quick question I can't seem to figure out. This code returns true:

Boolean testBool = true;
Boolean test = testBool instanceof Object;
System.out.println(test);

However, I thought Boolean was a primitive type and when I try this same logic with any other primitive type I get a compiler error that says: unexpected type required: reference found: int

I'm sure there's just something small I'm missing. Thanks for your help!


回答1:


boolean is a primitive type; java.lang.Boolean is its wrapper class.

You'll notice that all the primitive types have companion wrapper classes (e.g., int and java.lang.Integer, etc.)




回答2:


Boolean with uppercased initial B wraps a boolean primitive. As the docs say:

The Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field whose type is boolean.

Autoboxing can implicitly move between such boxed types and the corresponding primitives.



来源:https://stackoverflow.com/questions/2306257/boolean-instanceof-object-is-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!