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
BOOLEAN can have TRUE or FALSE values. BOOLEAN can also have an “unknown” value, which is represented by NULL.
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.
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) { ...}
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With