Raheel
Raheel

Reputation: 5163

Boolean(Object) getters in java

Lets say I have class foo in which I have a Boolean (not boolean) variable bar:

class foo {
    Boolean bar;

    Boolean isBar(){
        return bar;
    }

    boolean isBar(){
        return bar.booleanValue();
    }
}

Which of the above methods is the right way in Java.

I know both will work but I want to know what is the coding convention in Java regarding this matter?

Upvotes: 5

Views: 5332

Answers (3)

Maroun
Maroun

Reputation: 95968

a boolean is a primitive, it can be true or false. Boolean is an object wrapper for boolean. Boolean can be true, false and null. Unless you need this null, use boolean since it's cheaper for memory.

Boolean has many helper methods, for example, you can have a Boolean from a String by using Boolean.valueOf(theString); which can be "false" or "true", instead of doing

if("true".equals(theString)) 
    primitiveBoolean = true;

Upvotes: 3

Harald K
Harald K

Reputation: 27094

Unless bar can be null, and this is something you want to model in your class, I would use:

class foo {
    boolean bar;

    boolean isBar(){
        return bar;
    }
}

It's simpler, faster and can't have NullPointerExceptions.

If, however, null is a valid value and you want model that, you should use Boolean/Boolean.

Note that your code:

Boolean bar;

boolean isBar() {
    return bar.booleanValue();
}

Or even the autoboxing variant:

Boolean bar;

boolean isBar() {
    return bar;
}

...may throw NullPointerExceptions. Especially the last one is very confusing.

Upvotes: 2

G-Man
G-Man

Reputation: 1331

if you will actualy be using the Boolean type your method should be

Boolean getBar(){
    return bar;
}

otherwise your field should be the primitive boolean type.

Upvotes: 11

Related Questions