I would like to understand the difference between the Boolean
and boolean
types in Java, specifically as they relate to GWT.
I know that methods are not supported but I want more info if it is available.
views:
1589answers:
7In Java, a boolean
is a literal true
or false
, while Boolean
is an object wrapper for a boolean
.
There is seldom a reason to use a Boolean
over a boolean
except in cases when an object reference is required, such as in a List
.
Boolean
also contains the static method parseBoolean(String s)
, which you may be aware of already.
I'm not sure if the GWT factor makes a difference but in general:
boolean is a java primitive type whereas Boolean is an object/reference type that wraps a boolean
Converting between primitives and objects like this is known as boxing/unboxing.
Here is more info:
http://javaeye.wordpress.com/2008/06/17/boxing-and-unboxing-conversion/
Why box you ask?
http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html
Java has primitive types (int, boolean, float, etc) and anytime you wish to use them as an instance of an object they are wrapped in an associated Class type. For example, booleans get wrapped by Booleans, int as Integer etc.
It has its benefits too. boolean has no helper methods (since it's not a class), but Boolean does. So, if you wanted to convert a string to a boolean you could try Boolean.valueOf("true").
Hope that helps.
It's fairly Simple and the same for GWT and Java:
- boolean can be yes or no
- Boolean can be yes, no or NULL.
So unless you need the NULL (like for example your loading the field from the database, and you want NULL to be different to false) then stick to boolean.
According to the GWT JRE emulation docs (http://code.google.com/webtoolkit/doc/1.6/RefJreEmulation.html) these methods are supported on the Boolean type: Boolean(boolean), Boolean(String), parseBoolean(String), toString(boolean), valueOf(boolean), valueOf(String), booleanValue(), compareTo(Boolean), equals(Object), hashCode(), toString()
as to the difference between boolean and Boolean object types. Boolean objects can be in 3 states, so it is not exactly the same. But if that makes a difference in GWT (performance wise) I don't have a clue, my guess is that it does not matter much since the GWT compiler will optimize the code and most operations could simply map to native javascript boolean operations.
But as usual: to be certain you must measure (and take into account that this might differ based on what browser/version you are measuring).
The Boolean object type is normally not used very often since the boolean native type is more natural (you don't need to check for null all the time).
Because Boolean can be null, it can be used for lazy loading.
if(hasRoots == null){
calculateRoots();
}