2

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?

hubalazs
  • 448
  • 4
  • 13

5 Answers5

2

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.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

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

Ahmed Gamal
  • 1,666
  • 1
  • 17
  • 25
2

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.
Sundeep Badhotiya
  • 810
  • 2
  • 9
  • 14
0

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?

Community
  • 1
  • 1
Jaydeep Patel
  • 146
  • 2
  • 9
0

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

andrei
  • 2,934
  • 2
  • 23
  • 36