boolean
is a primitive type , that is, a number that occupies 1 byte (although it is not specified that it has this size) and is considered a type by value, that is, its value is its own identity, it exists in itself. The comparison of values is straightforward.
The default value is false
.
It can be implicitly converted to a text ("false" or "true") and a number (0 or 1) can be used to represent false or true in type where needed.
Boolean
is a class that encapsulates a boolean
e is a type by reference, so its actual value is a pointer that points to the Boolean value. Obviously the class derives Object
and has all characteristics of an object like any other.
This is a way to pass the data by reference in methods parameters or use where you need an indirection.
The default value of null
. It has 3 possible states, and the fact that you need the status null
is a reason to use it.
The comparison is given by the equals()
method, if you use the ==
operator, it will compare the pointers of the objects even though they have the same value. Unless you use booleanValue()
that grabs the primitive within the object, but then the comparison is not with the object but with primitives extracted from the classes.
The compiler does a trick for boxing to appear transparent, but it is creating a new instance in heap .
Boolean x = true; //na verdade é traduzido para o abaixo
Boolean x = Boolean.valueOf(true);
Imagine that in addition to the space occupied by the pointer (4 or 8 bytes) it still stores an object that can occupy 20 bytes or more depending on the architecture. All this because of a single bit.
Induction besides having a higher cost of allocation and copy generates more miss cache on the access that needs to occur in two steps: it accesses the value (pointer address) and then the value of the object.
The preference is always to use the primitive type, it is faster and takes up less memory. Given the inefficiency the option for the class only if it is really necessary to have a reference. An example of need in the current version is the use with generics (this will possibly change in Java 10).
ArrayList<Boolean> = lista = new ArrayList<>(); //válido
ArrayList<boolean> = lista = new ArrayList<>(); //inválido
See about this in What's the difference between "generics" (Java / C #) and "template" (C ++) and What are the differences between Generic Types in C # and Java? .
With methods:
void metodo(boolean x) {x = false;} //quando terminar o método, não muda nada no argumento
void metodo(Boolean x) {x = false;} //quando terminar o método, o argumento valerá false
Rumors :) Is it better to use primitive types in Java?
For comparison effect C # gets all 3 main effects reported with the primitive type: use as generic type, can be passed explicitly by reference without doing boxing and has the void option bool?
is still a value type occupying only 2 bytes in total (could be 1 if there was optimization).