user4583559
user4583559

Reputation: 65

Declaring boolean variable

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

Answers (5)

andrei
andrei

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

Jaydeep Patel
Jaydeep Patel

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

Suresh Atta
Suresh Atta

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

Sundeep Badhotiya
Sundeep Badhotiya

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.

  • boolean can be yes or no.
  • Boolean can be yes, no or NULL.

Upvotes: 2

Ahmed Gamal
Ahmed Gamal

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

Related Questions