Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean references are null

Can anyone explain why this code results in the below output?

@Test
public void testBooleanArray() {
    Boolean[] ab = new Boolean[]{a, b};

    a = new Boolean(true);
    b = new Boolean(false);

    for(Boolean x : ab) {
        System.out.println(x);
    }
}

Result:

null
null

Should the array ab not holds pointers to object a and object b, and therefore output:

true
false
like image 609
StuPointerException Avatar asked Oct 15 '13 15:10

StuPointerException


People also ask

Can a Boolean value be null?

BOOLEAN can have TRUE or FALSE values. BOOLEAN can also have an “unknown” value, which is represented by NULL.

What does Boolean null mean?

A Boolean object can NEVER have a value of null. If your reference to a Boolean is null, it simply means that your Boolean was never created.

How do you handle a Boolean null?

You can use the class Boolean instead if you want to use null values. Boolean is a reference type, that's the reason you can assign null to a Boolean "variable". Example: Boolean testvar = null; if (testvar == null) { ...}

Can Boolean be empty?

There's not a material difference between a Boolean field set to false and a Boolean field set to the null value. Even via API, the current value will be materialized as false in either case. Another way of looking at it is a field update request supports nulls, but field storage does not. A Boolean can't be blank.


2 Answers

a = new Boolean(true);
b = new Boolean(false);

This does not change the objects that a and b were pointing to(the elements in the array). It points them to new objects.

It is not modfying the array

To illustrate:

Boolean a = new Boolean(true);
Boolean b = new Boolean(false);
Boolean c = a;
Boolean d = b;
a = new Boolean(false);
b = new Boolean(true);

c and d will still be true/false respectively. This is the same thing that is happening with the array, except your array reference isn't named the same way.

like image 129
Cruncher Avatar answered Sep 19 '22 18:09

Cruncher


You have to initialize your booleans before assigning them.

Boolean[] ab = new Boolean[]{a, b};

a = new Boolean(true);
b = new Boolean(false);

to

a = new Boolean(true);
b = new Boolean(false);

Boolean[] ab = new Boolean[]{a, b};

This is before with Objects, you copy the reference to the object, and with new statement, you create a new object, the first a,b were null when assigning.

like image 21
RamonBoza Avatar answered Sep 17 '22 18:09

RamonBoza