Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use the Boolean.valueOf() method vs (or Java 1.5 autoboxing) to create Boolean objects

Which is the better practice between Boolean.valueOf() and Java 1.5 autoboxing to create Boolean from booleans and why ?

like image 218
Geek Avatar asked Jul 26 '12 16:07

Geek


1 Answers

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.

like image 85
Tomasz Nurkiewicz Avatar answered Nov 01 '22 19:11

Tomasz Nurkiewicz