263

There are discussions around Integer vs int in Java. The default value of the former is null while in the latter it's 0. How about Boolean vs boolean?

A variable in my application can have 0/1 values. I would like to use boolean/Boolean and prefer not to use int. Can I use Boolean/boolean instead?

2
  • 7
    For system design reasons I would choose Boolean since it has the option "The user didn't decide yet" which is neither equals with "true", nor "false". I would use boolean primitive only in cases if I am 100% sure true/false options are enough. In database NULL option is usually available without problem (or by just removing NOT NULL restrictions on later demand) Dec 12, 2014 at 9:45
  • 2
    Exact duplicate of What's the difference between boolean and Boolean in Java? (because GWT doesn't make a difference). Jan 7, 2016 at 22:23

8 Answers 8

373

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 The second will save you a lot more memory, so go for it

Now choose your way.

7
  • 78
    You could have phrased this as "the second will save you a lot more memory, so go for it". The useful methods on Boolean can mostly be invoked without having an instance of it. Sep 16, 2010 at 16:29
  • 4
    As long as you use instead Boolean.valueOf(value) of new Boolean(value), memory shouldn't be a concern.
    – Greg Case
    Sep 16, 2010 at 18:22
  • 4
    for AsyncTask, you can only use Boolean instead of boolean.
    – Raptor
    Jan 13, 2014 at 10:03
  • 164
    It should be noted the a Boolean actually has 3 states... true, false and null where a boolean has the logical 2 states (true and false) Jun 6, 2014 at 15:46
  • 5
    booleans don't safe you any memory over Boolean. Boolean has two constant instances, TRUE and FALSE, they are there regardless if you use a Boolean, or not. A boolean inside of an object is alway as big as the word size of the VM, so it is usually the same size as a reference/pointer to a Boolean. On the stack that might be different. But when it is jitted, it is safe to assume it has the size of a machine word fitting to the CPU. However: for arrays that is very different!. Apr 6, 2017 at 22:08
64

Boolean wraps the boolean primitive type. In JDK 5 and upwards, Oracle (or Sun before Oracle bought them) introduced autoboxing/unboxing, which essentially allows you to do this

boolean result = Boolean.TRUE;

or

Boolean result = true; 

Which essentially the compiler does,

Boolean result = Boolean.valueOf(true);

So, for your answer, it's YES.

3
  • 10
    Note: You can't always safely assign a Boolean to a boolean. If your Boolean is null and you try to assign it to a boolean, it will throw a NullPointerException at runtime. Mar 22, 2018 at 10:09
  • if Boolean a class then why value is always false even if I changed the value from another class referencing to the same Boolean variable? what is the point of this Boolean then if we can't reference to from different instance classes / pass as argument?
    – user924
    Apr 22, 2018 at 14:05
  • found an answer, we can use AtomicBoolean and reference it from difference classes
    – user924
    Apr 22, 2018 at 14:09
41

I am a bit extending provided answers (since so far they concentrate on their "own"/artificial terminology focusing on programming a particular language instead of taking care of the bigger picture behind the scene of creating the programming languages, in general, i.e. when things like type-safety vs. memory considerations make the difference):

int is not boolean

Consider

    boolean bar = true;      
    System.out.printf("Bar is %b\n", bar);
    System.out.printf("Bar is %d\n", (bar)?1:0);
    int baz = 1;       
    System.out.printf("Baz is %d\n", baz);
    System.out.printf("Baz is %b\n", baz);

with output

    Bar is true
    Bar is 1
    Baz is 1
    Baz is true

Java code on 3rd line (bar)?1:0 illustrates that bar (boolean) cannot be implicitly converted (casted) into an int. I am bringing this up not to illustrate the details of implementation behind JVM, but to point out that in terms of low level considerations (as memory size) one does have to prefer values over type safety. Especially if that type safety is not truly/fully used as in boolean types where checks are done in form of

if value \in {0,1} then cast to boolean type, otherwise throw an exception.

All just to state that {0,1} < {-2^31, .. , 2^31 -1}. Seems like an overkill, right? Type safety is truly important in user defined types, not in implicit casting of primitives (although last are included in the first).

Bytes are not types or bits

Note that in memory your variable from range of {0,1} will still occupy at least a byte or a word (xbits depending on the size of the register) unless specially taken care of (e.g. packed nicely in memory - 8 "boolean" bits into 1 byte - back and forth).

By preferring type safety (as in putting/wrapping value into a box of a particular type) over extra value packing (e.g. using bit shifts or arithmetic), one does effectively chooses writing less code over gaining more memory. (On the other hand one can always define a custom user type which will facilitate all the conversion not worth than Boolean).

keyword vs. type

Finally, your question is about comparing keyword vs. type. I believe it is important to explain why or how exactly you will get performance by using/preferring keywords ("marked" as primitive) over types (normal composite user-definable classes using another keyword class) or in other words

boolean foo = true;

vs.

Boolean foo = true;

The first "thing" (type) can not be extended (subclassed) and not without a reason. Effectively Java terminology of primitive and wrapping classes can be simply translated into inline value (a LITERAL or a constant that gets directly substituted by compiler whenever it is possible to infer the substitution or if not - still fallback into wrapping the value).

Optimization is achieved due to trivial:

"Less runtime casting operations => more speed."

That is why when the actual type inference is done it may (still) end up in instantiating of wrapping class with all the type information if necessary (or converting/casting into such).

So, the difference between boolean and Boolean is exactly in Compilation and Runtime (a bit far going but almost as instanceof vs. getClass()).

Finally, autoboxing is slower than primitives

Note the fact that Java can do autoboxing is just a "syntactic sugar". It does not speed up anything, just allows you to write less code. That's it. Casting and wrapping into type information container is still performed. For performance reasons choose arithmetics which will always skip extra housekeeping of creating class instances with type information to implement type safety. Lack of type safety is the price you pay to gain performance. For code with boolean-valued expressions type safety (when you write less and hence implicit code) would be critical e.g. for if-then-else flow controls.

1
  • Incredibly well explained, Yauhen! Jan 25 at 9:39
16

You can use the Boolean constants - Boolean.TRUE and Boolean.FALSE instead of 0 and 1. You can create your variable as of type boolean if primitive is what you are after. This way you won't have to create new Boolean objects.

9

One observation: (though this can be thought of side effect)

boolean being a primitive can either say yes or no.

Boolean is an object (it can refer to either yes or no or 'don't know' i.e. null)

5

Basically boolean represent a primitive data type where Boolean represent a reference data type. this story is started when Java want to become purely object oriented it's provided wrapper class concept to over come to use of primitive data type.

boolean b1;
Boolean b2;

b1 and b2 are not same.

2

You can use Boolean / boolean. Simplicity is the way to go. If you do not need specific api (Collections, Streams, etc.) and you are not foreseeing that you will need them - use primitive version of it (boolean).

  1. With primitives you guarantee that you will not pass null values.
    You will not fall in traps like this. The code below throws NullPointerException (from: Booleans, conditional operators and autoboxing):

    public static void main(String[] args) throws Exception { Boolean b = true ? returnsNull() : false; // NPE on this line. System.out.println(b); } public static Boolean returnsNull() { return null; }

  2. Use Boolean when you need an object, eg:

    • Stream of Booleans,
    • Optional
    • Collections of Booleans
1

Boolean is threadsafe, so you can consider this factor as well along with all other listed in answers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.