What will be the result of the following program execution?

public class Test {
    public static void main(String[] args) {
        Integer i1 = 1000;
        Integer i2 = 1000;
        System.out.println(i1 == i2);
        System.out.println(i1 == 1000);
    }
}
Explanation

Each time you convert a value of 1000 into an object wrapper a new Integer instance is created. Therefore, first comparison will result in false. Note: For values from -128 to 127 an object will be taken from the pool of Integers, and result of comparison will be true.

If the == operation compares primitives and object wrappers, then object wrappers are converted into primitives. Therefore, second comparison will result in true.

It is an important addition. Thanks, @ashram. Updated explanation.

2016 Feb 2, 6:04:14 PM

"Each time you convert a value of 1000 into an object wrapper a new Integer instance is created." It is relevant to say that for values from -128 to 127 an object will be taken from the pool of Integers.

2016 Jan 31, 8:12:38 PM

Следи за CodeGalaxy

Мобильное приложение Beta

Get it on Google Play
Обратная Связь
Продолжайте изучать
тесты по Java
Cosmo
Зарегистрируйся сейчас
или Подпишись на будущие тесты