Default value of 'boolean' and 'Boolean' in Java - java

What are the default values of boolean (primitive) and Boolean (primitive wrapper) in Java?

The default value for a Boolean (object) is null.
The default value for a boolean (primitive) is false.

The default value of any Object, such as Boolean, is null.
The default value for a boolean is false.
Note: Every primitive has a wrapper class. Every wrapper uses a reference which has a default of null. Primitives have different default values:
boolean -> false
byte, char, short, int, long -> 0
float, double -> 0.0
Note (2): void has a wrapper Void which also has a default of null and is it's only possible value (without using hacks).

boolean
Can be true or false.
Default value is false.
(Source: Java Primitive Variables)
Boolean
Can be a Boolean object representing true or false, or can be null.
Default value is null.

If you need to ask, then you need to explicitly initialize your fields/variables, because if you have to look it up, then chances are someone else needs to do that too.
The value for a primitive boolean is false as can be seen here.
As mentioned by others the value for a Boolean will be null by default.

Boolean is an Object. So if it's an instance variable it will be null. If it's declared within a method you will have to initialize it, or there will be a compiler error.
If you declare as a primitive i.e. boolean. The value will be false by default if it's an instance variable (or class variable). If it's declared within a method you will still have to initialize it to either true or false, or there will be a compiler error.

An uninitialized Boolean member (actually a reference to an object of type Boolean) will have the default value of null.
An uninitialized boolean (primitive) member will have the default value of false.

There is no default for Boolean. Boolean must be constructed with a boolean or a String. If the object is unintialized, it would point to null.
The default value of primitive boolean is false.
http://download.oracle.com/javase/6/docs/api/java/lang/Boolean.html
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

class BooleanTester
{
boolean primitive;
Boolean object;
public static void main(String[] args) {
BooleanTester booleanTester = new BooleanTester();
System.out.println("primitive: " + booleanTester.getPrimitive());
System.out.println("object: " + booleanTester.getObject());
}
public boolean getPrimitive() {
return primitive;
}
public Boolean getObject() {
return object;
}
}
output:
primitive: false
object: null
This seems obvious but I had a situation where Jackson, while serializing an object to JSON, was throwing an NPE after calling a getter, just like this one, that returns a primitive boolean which was not assigned. This led me to believe that Jackson was receiving a null and trying to call a method on it, hence the NPE. I was wrong.
Moral of the story is that when Java allocates memory for a primitive, that memory has a value even if not initialized, which Java equates to false for a boolean. By contrast, when allocating memory for an uninitialized complex object like a Boolean, it allocates only space for a reference to that object, not the object itself - there is no object in memory to refer to - so resolving that reference results in null.
I think that strictly speaking, "defaults to false" is a little off the mark. I think Java does not allocate the memory and assign it a value of false until it is explicitly set; I think Java allocates the memory and whatever value that memory happens to have is the same as the value of 'false'. But for practical purpose they are the same thing.

Related

error: incomparable types: boolean and <null>

if(savedInstanceState.getBoolean("mybool") == null)
I get error error: incomparable types: boolean and <null>
I want to check if mybool does not exist, how do I do that?
My onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);}
Elsewhere in my code:
savedInstanceState.putBoolean("mybool", true);
The docs say that getBoolean(String key) returns a boolean, i.e. a primitive type. Primitive types are never null. In this case it's either true or false. Compared to the wrapper type Boolean, which can be null.
Furthermore, the docs say if the key isn't present, this method simply returns false.
If you want to check if mybool exists or not, use containsKey(String key) instead. (Again, refer to the docs)
If you want to check whether "mybool" exists in the Bundle object:
if (!savedInstanceState.containsKey("mybool")) {
// your code here
}
Try to use Boolean instead of boolean i.e. use the Class instead if the primitive type. I do not recommend this though. Boolean should be either true or false.
This issue you are having is your understanding of how primitives work. Primitive types, including boolean, cannot be null. Even if you do not assign a value to them when you define the variable, there is a value assigned to them.
In the case of the primitive type boolean, the value is assigned as false when initialized if you do not assign a boolean value to the variable. See here for more information on how primitives are treated and what their default values are.

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?
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.
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
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.
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?
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

What the difference between Boolean.TRUE and true

Firstly, I have
private Map<String, Boolean> mem = new HashMap<String, Boolean>();
And then:
if (wordDict.contains(s) || Boolean.TRUE==mem.get(s)) {
return true;
}
why can't I use "mem.get(s)==true" in the if statement. There will be a error "Line 6: java.lang.NullPointerException"
I think I still cannot understant wrapper class well. Please give me some guidance. Thank you!
if mem.get(s) is null and will be compared with a primitive boolean value, java will make autoboxing. It means it will call null.booleanValue().
Thats why you get a NPE.
looks that mem.get(s) returns Boolean type result. In java there are two types for handling logical values. Boolean object type and boolean primitive type.
To evaluate logical expression for if statement, java converts Boolean to boolean using autoboxing.
But if your method returns null instead of Boolean object, then java is unable to unbox this value to boolean primitive type. And you get NullPointerException.
This is more a logical problem than a languagebased. if(mem.contains(s) || Boolean.TRUE == mem.get(s)) will only check the second part of the condition, if s isn't in mem. Thus the comparison is equivalent to Boolean.TRUE == null. Since Boolean.TRUE is a Boolean object, the comparison is between two references (and will always return false). boolean on the other hand is a primitive type and thus the Boolean retrieved from mem has to be converted first. Since it's null it can't be converted to the primitive type.
Any time the dictionary does not contain s (wordDict.contains(s) is false), the second condition (mem.get(s) == true) is evaluated.
In Java's library Maps, attempting to obtain the value for a key which isn't present returns null. So every time that key isn't in the mem map, null is returned, and compared (using ==) with true. When the Boolean type gets compared with, or assigned to, a boolean value, it is 'autounboxed'. This means the Boolean.booleanValue() method is called. If the Boolean is null, this is what causes the exception, because it means calling null.booleanValue(). null is not anything, so it doesn't know how to be a boolean!
The wrapper classes are useful constructs which enable the primitive types to interoperate with types inheriting from Object, that is, reference types (everything else). When you deal with primitive types ('value' types), their values are directly present in the location they're described in - either as part of the memory being used to execute the current function (for local variables) or as part of the memory space allocated to an object in its memory space (for field variables). When you deal with reference types (those inheriting from Object, including Boolean and the other wrapper types), the data being referred to instead exists in a memory space called the Heap. Alongside this Heap memory allocation, in order to know where that object is, the entity analogous to the value for value types is in fact a reference to the memory location of the object, stored as a local variable or a field variable, not the value or data of the object itself. This is what enables these to be null: a null reference says that this variable points to nothing in particular. (Read about Stack and Heap allocation for more detail.)
The reason you're safe comparing to Boolean.TRUE is because on Object types, like Boolean (and any of the wrapper classes for primitive types), the variable of type Boolean is in fact a reference. This means the == operator is actually checking if the references are the same - i.e. if the actual object in memory is the same one (has the same memory location), not if they are 'equal' by some value-based definition of 'equal'. You don't want this, because you can get surprising results like new Boolean(true) == new Boolean(true) returning false. This is incidentally why we have the equals method - this should be defined by any class for an object that wants to be compared by value rather than by reference. On the other hand, for the primitive value types, like boolean, the == operator literally compares the value. This is why it's useful to have the wrapper types box and unbox automatically - a Boolean variable (without being 'dereferenced' - finding the value it points to) is actually a reference value, referring to a memory location. A boolean variable is an actual boolean value. Hence, without unboxing and boxing automagically, it would make no sense to try to compare the two.
If you want to make sure that the value of mem.get(s) is neither null, nor false, use something like mem.containsKey(s) && mem.get(s) == true. The first check ensures that there will be no null reference.

Default initialization in java

I have a confusion about variable initialization in Java. As I understand, class variables get default initialization while local variables are not initialized by default. However, if I create an array inside a method using the new keyword, it does get initialized by default. Is this true of all objects? Does using the new keyword initialize an object regardless of whether it's a class variable or local variable?
From Java Language Specification
Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10):
For type byte, the default value is zero, that is, the value of
(byte)0.
For type short, the default value is zero, that is, the value of (short)0.
For type int, the default value is zero, that is, 0.
For type long, the default value is zero, that is, 0L.
For type float, the default value is positive zero, that is, 0.0f.
For type double, the default value is positive zero, that is, 0.0d.
For type char, the default value is the null character, that is, '\u0000'.
For type boolean, the default value is false.
For all reference types (§4.3), the default value is null
After further investigation, primitives will always initialize to the default only when they are member variables, local variables will throw a compile error if they are not initialized.
If you create an array of primitives they will all be initialized by default (this is true for both local and member arrays), an array of objects you will need to instantiate each one.
Is this true of all objects? Does using the new keyword initialize an
object regardless of whether it's a class variable or local variable?
When you use new keyword. it means that you have initialized your Object. doesn't matter if its declared at method level or instance level.
public void method(){
Object obj1;// not initialized
Object obj2 = new Object();//initialized
}

Why change boolean primitive value into a boolean object reference?

I am reading Effective Java and in the first chapter the first example changes a boolean primitive value into a boolean object reference:
public static Boolean valueOf(boolean b)
{
return b ? Boolean.TRUE : Boolean.FALSE;
}
My questions are:
What is the different between boolean primitive value and boolean object reference?
What is the reason to do this?
You cannot use primitives in generics. You cannot do this:
List<boolean> x;
but you can do this:
List<Boolean> x;
Remember that the primitive boolean has two possible values: true or false. The object Boolean has three: true, false, and null. That is sometimes very useful.
A primitive cannot be used in all contexts. For instance, when used in any of the collection classes, an object type is required. This is mostly done for you, anyway, by auto-boxing. But you should still know about it, or you will get bitten at one point.
Another thing is that an object type can contain null. In cases where you need to differentiate between true, false and unknown, using Boolean can be an easy solution.
1> Boolean is wrapper class for boolean
Wrapper classes are used to represent primitive values when an Object
is required. Wikipedia
wrapper class is used to apply some methods and calculation, which is not possible using primitive data types.
2> it depends upon situations.
I believe the most common uses for Boolean are for use in generic function object and, unfortunately, reflection.
For instance:
boolean exists = java.security.AccessController.doPrivileged(
new PrivilegedAction<>() {
public Boolean run() {
return file.exists();
}
}
);
(Probably less boilerplate in Java SE 8.)

Categories

Resources