Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 286
Raheel Avatar asked Jun 13 '13 07:06

Raheel


3 Answers

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.

like image 53
G-Man Avatar answered Sep 30 '22 17:09

G-Man


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;
like image 26
Maroun Avatar answered Sep 30 '22 17:09

Maroun


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.

like image 35
Harald K Avatar answered Sep 30 '22 17:09

Harald K