Java – added = = confused behavior
•
Java
There is already an answer to this question: > integer wrapper objects share the same instances only within the value 127? 5
Integer i1 = 127; Integer i2 = 127; System.out.println(i1++ == i2++); System.out.println(i1 == i2);
As a person interested in Java, I gave my ideas and got the following results
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
Tell me The first line is true and the second line is false
I really appreciate an explanation
The second question is whether this Java is specific, or whether this example is applicable to C language?
Solution
Integer i1 = 127;
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 equals () is used, it will return true as an integer. The = = operator is only applicable to cached values Since 128 is out of the cache range, values above 128 will not be cached, so you need to use the equals () method to check whether the 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
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码