Boolean vs boolean in Java
Asked Answered
T

8

264

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?

Twinscrew answered 16/9, 2010 at 16:20 Comment(2)
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)Esmerolda
Exact duplicate of What's the difference between boolean and Boolean in Java? (because GWT doesn't make a difference).Handset
S
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.

Sculley answered 16/9, 2010 at 16:23 Comment(7)
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.Xerxes
As long as you use instead Boolean.valueOf(value) of new Boolean(value), memory shouldn't be a concern.Sarita
for AsyncTask, you can only use Boolean instead of boolean.Adanadana
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)Heavensent
If you plan in putting the boolean inside a collection you need to use Boolean, no other way to do it.Critta
I think that if I use Boolean and pass that into a method and then its state gets changed by the caller, that change will also be reflected in the method. I have a case where my Boolean is 'connected'. In transports all kinds of things can go bad and one can be in the middle of something and get disconnected. If there is some processing going on in the called method, I want it to know that the state has changed to disconnected. I hope the Boolean will carry that info; I know boolean wont.Bernardobernarr
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!.Subaquatic
S
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.

Selfsupport answered 16/9, 2010 at 16:33 Comment(3)
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.Reina
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?Indissoluble
found an answer, we can use AtomicBoolean and reference it from difference classesIndissoluble
D
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.

Displode answered 29/11, 2012 at 22:39 Comment(1)
Incredibly well explained, Yauhen!Gastongastralgia
R
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.

Rangel answered 16/9, 2010 at 16:25 Comment(0)
O
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)

Obscene answered 12/11, 2018 at 12:21 Comment(0)
N
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.

Neilson answered 2/2, 2016 at 7:45 Comment(0)
E
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
Exsert answered 10/12, 2018 at 12:17 Comment(0)
A
1

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

Asthenia answered 12/2, 2021 at 8:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.