Hello. Pass the test. Here, faced with incomprehensibility. Question:
What will be displayed on the screen?
Integer a = 128; Integer b = 128; Integer c = -128; Integer d = -128; System.out.println(a == b); System.out.println(c == d); I answered false, false . Wrong. Explanation:
To increase the boxing conversion efficiency (conversion of a primitive type value to an object of the corresponding wrapper class), pre-created objects of the Integer (-128 .. 127), Byte (-128 .. 127), Short (-128) classes are used for small integer values. .. 127), Character (0 .. 127). These sets are usually referred to as a cache (eg, integer cache) or a pool (eg, integer pool). Therefore, c == d gives true. For the remaining values, a new object is created each time during the boxing conversion. Therefore, a == b gives false.
And one more question:
Integer ii = 1000; Integer jj = 2000; System.out.print((ii * 2 == jj) ? "yes " : "no "); System.out.print((jj / 2 == ii) ? "yes " : "no "); System.out.print((ii * 2 == jj) ^ (jj / 2 == ii) ? "yes " : "no "); I replied that there would be no no no . Wrong. Explanation:
When performing any arithmetic operations (multiplication, division, ...), the objects of the wrapper classes (Integer) are automatically expanded to values of the primitive type (int). The result of any arithmetic operation will also be a value of a primitive type. If using == compares the value of the primitive type and the wrapper object, then the object automatically expands and the two primitives are compared. The result of the ^ (exclusive OR) operation will be false, since both operands are true.
Why the second question does not specify caching from -128 to 127? Thank.