Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puzzling behaviour of == after postincrementation [duplicate]

Someone postulated in some forum thread that many people and even experienced Java Developers wouldn't understand the following peace of Java Code.

Integer i1 = 127;
Integer i2 = 127;
System.out.println(i1++ == i2++);
System.out.println(i1 == i2);

As a person with some interest in Java I gave it my thoughts and came to the following result.

System.out.println(i1++ == i2++);
// True, since we first check for equality and increment both variables afterwards.

System.out.println(i1 == i2);
// True again, since both variables are already incremented and have the value 128

Eclipse tells me otherwise. The first line is true and the second is false.

I really would appreciate an explanation.

Second question. Is this Java specific or does this example hold for example for the C based languages, too?

like image 948
Aufwind Avatar asked Feb 25 '13 10:02

Aufwind


2 Answers

Integer i1 = 127;
Integer i2 = 127;
System.out.println(i1++ == i2++); 
// here i1 and i2 are still 127 as you expected thus true
System.out.println(i1 == i2); 
// here i1 and i2 are 128 which are equal but not cached
    (caching range is -128 to 127), 

In case 2 if you use equals() it'd return true as == operator for integers only works for cached values. as 128 is out of cache range the values above 128 will not be cached, thus youhave to use equals() method to check if two integer instances above 127 are true

TEST:

Integer i1 = 126;
    Integer i2 = 126;
    System.out.println(i1++ == i2++);// true
    System.out.println(i1 == i2); //true



 Integer i1 = 126;
        Integer i2 = 126;
        System.out.println(i1++ == i2++);// true
        System.out.println(i1.equals(i2)); //true

  Integer i1 = 128;
        Integer i2 = 128;
        System.out.println(i1++ == i2++);// false
        System.out.println(i1==i2); //false

  Integer i1 = 128;
        Integer i2 = 128;
        System.out.println(i1++.equals(i2++));// true
        System.out.println(i1.equals(i2)); //true
like image 56
PermGenError Avatar answered Nov 16 '22 23:11

PermGenError


As explained this is due to Integer caching. For fun, you can run the program with the following JVM option:

-XX:AutoBoxCacheMax=128

and it will print true twice (option available on hostpot 7 - not necessarily on other JVMs).

Note that:

  • this is JVM specific
  • the modified behaviour is compliant with the JLS which says that all values between -128 and +127 must be cached but also says that other values may be cached.

Bottom line: the second print statement is undefined in Java and can print true or false depending on the JVM implementation and/or JVM options used.

like image 1
assylias Avatar answered Nov 17 '22 01:11

assylias