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?
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.
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;
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 NullPointerException
s.
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 NullPointerException
s. Especially the last one is very confusing.
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