Geek
Geek

Reputation: 27219

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 ?

Upvotes: 8

Views: 1349

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 341003

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.

Upvotes: 14

Related Questions