Reputation: 65
I just saw a code from another developer.
private static boolean _menuNeedsUpdate = false;
private static Boolean _userIsLoggingIn = Boolean.valueOf(false);
I want to know the differences between these two declarations. Can any one please clarify this?
Upvotes: 2
Views: 161
Reputation: 2940
As others said, the first declaration is a primitive while the second is wrapper class.
I would like to add that the second declaration creates a warning when using Java 5 or newer.
Declaring _userIsLoggingIn
like
private static Boolean _userIsLoggingIn = false;
instead of
private static Boolean _userIsLoggingIn = Boolean.valueOf(false);
will use Boolean.FALSE
, avoiding the creation of a new Boolean instance
Upvotes: 0
Reputation: 156
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.
More info : What's the difference between boolean and Boolean in Java?
Upvotes: 0
Reputation: 121998
The first one is a primitive boolean
with default value false
.
The second one is a Wrapper class of Boolean
with default value false
.
Apart, I can't see any more difference.
Edit : (Thankyou @carsten @sasha)
Apart from the declaration, another point worth mentioning is with the second declaration the value of _userIsLoggingIn
may become null
later on where as the primitive cannot.
Upvotes: 2
Reputation: 868
Frist one is java primitive and second one is an object/refrence types that wraps a boolean.
Converting between primitives and objects like this is known as boxing/unboxing.
Upvotes: 2
Reputation: 1696
yes you can use Boolean/boolean instead.
First one is Object and second one is primitive type
On first one, you will get more methods which will be useful
Second one is cheap considering memory expense.
Now choose your way
Upvotes: 2