Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean instanceof Object is true?

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!

like image 263
Jon Avatar asked Dec 10 '25 06:12

Jon


2 Answers

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.

like image 71
Alex Martelli Avatar answered Dec 15 '25 08:12

Alex Martelli


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.)

like image 20
duffymo Avatar answered Dec 15 '25 07:12

duffymo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!