Which is the better practice between Boolean.valueOf()
and Java 1.5 autoboxing
to create Boolean
from booleans
and why ?
Autoboxing of boolean
is transparently translated to Boolean.valueOf()
by the compiler:
boolean b = true;
Boolean bb = b;
is translated to:
iconst_1
istore_1 //b = 1 (true)
iload_1 //b
invokestatic #2; //Method java/lang/Boolean.valueOf:(Z)Ljava/lang/Boolean;
astore_2 //bb = Boolean.valueOf(b)
Use whichever you find more useful and readable. Since using Boolean.valueOf()
is not giving you anything except extra typing, you should aim for autoboxing.
Situation complicates when you think about opposite conversion - from Boolean
to boolean
. This time Boolean.booleanValue()
is called transparently for you by the compiler, which can theoretically cause NullPointerException
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With