What number of different objects will variables b1 - b11 refer to after the following code execution?

Boolean b1 = true;
Boolean b2 = true;
Boolean b3 = true;
Boolean b4 = true;
Boolean b5 = true;
Boolean b6 = true;
Boolean b7 = true;
Boolean b8 = true;
Boolean b9 = new Boolean(true);
Boolean b10 = new Boolean(true);
Boolean b11 = new Boolean(true);
Explanation
In order to perform an unboxing conversion all the commands of the "b1 = true" type are implicitly replaced by "b1 = Boolean.valueOf(true)". A valueOf() method, in turn, returns a previously created object - Boolean.TRUE.
Therefore, b1-b8 variables refer to the same object (Boolean.TRUE), but separate instances are created for variables b9-b11. So there will be 4 different objects.

It reminds me of how strings are created in string pool

2022 Aug 21, 5:20:53 PM

It is important to understand how to use it ...

2018 Jun 8, 8:52:39 AM

@sergeyst95 ^__^

2017 May 17, 11:48:54 PM

Loved it :)

2016 Dec 10, 10:54:04 PM

@epicminerbackup , maybe this will help https://coderanch.com/t/459826/java/Reference-equality-Boolean-reference

2016 Oct 26, 9:16:40 AM

I still don't exactly understand this one

2016 Oct 25, 12:00:54 PM

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Продовжуйте вивчати
тести з Java
Cosmo
Зареєструйся Зараз
або Підпишись на майбутні тести