What will be the output of the following code? (JDK version >= 1.5)

public static void main(String[] args) {
    Integer a = 12;
    Integer b = 12;
    Integer c = 128;
    Integer d = 128;
    System.out.println(a == b);
    System.out.println(c <= d);
    System.out.println(c >= d);
    System.out.println(c == d);
}
Explanation
The Java compiler evaluated an expression of Integer = ; to Integer = Integer.valueOf();.
Starting from JSE5.0 the compiler is caching Integer values between -128..127 (byte size). Hence, if the number is in the range mentioned above, the Integer.valueOf() method will always return an already existing object, corresponding to the requested int number, from a pre-generated Integer objects array. Otherwise, a new Integer object will be created.
Since == operator compares the object references, a==b will return true, because they have both been pointed to the same pre-generated object, but c==d will return false, because they point to separately created objects.
The compiler evaluates the c <= d; and c >= d; expressions to c.intValue() <= d.intValue() and c.intValue() >= d.intValue() which is equivalent to 128 <= 128 and 128 >= 128, which are both true.

Слідкуй за CodeGalaxy

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

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