Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 128==128 false but 127==127 is true when comparing Integer wrappers in Java?

People also ask

Can you use == to compare integers?

To compare integer values in Java, we can use either the equals() method or == (equals operator). Both are used to compare two values, but the == operator checks reference equality of two integer objects, whereas the equal() method checks the integer values only (primitive and non-primitive).

How do you compare two Integer values?

Syntax : public static int compare(int x, int y) Parameter : x : the first int to compare y : the second int to compare Return : This method returns the value zero if (x==y), if (x < y) then it returns a value less than zero and if (x > y) then it returns a value greater than zero.

How do you compare two integers equal in Java?

To check two numbers for equality in Java, we can use the Equals() method as well as the == operator. Firstly, let us set Integers. Integer val1 = new Integer(5); Integer val2 = new Integer(5); Now, to check whether they are equal or not, let us use the == operator.

What is Integer caching in Java?

Java Integer Cache Implementation: In Java 5, a new feature was introduced to save the memory and improve performance for Integer type objects handling. Integer objects are cached internally and reused via the same referenced objects. This is applicable for Integer values in the range between –128 to +127.


When you compile a number literal in Java and assign it to a Integer (capital I) the compiler emits:

Integer b2 =Integer.valueOf(127)

This line of code is also generated when you use autoboxing.

valueOf is implemented such that certain numbers are "pooled", and it returns the same instance for values smaller than 128.

From the java 1.6 source code, line 621:

public static Integer valueOf(int i) {
    if(i >= -128 && i <= IntegerCache.high)
        return IntegerCache.cache[i + 128];
    else
        return new Integer(i);
}

The value of high can be configured to another value, with the system property.

-Djava.lang.Integer.IntegerCache.high=999

If you run your program with that system property, it will output true!

The obvious conclusion: never rely on two references being identical, always compare them with .equals() method.

So b2.equals(b3) will print true for all logically equal values of b2,b3.

Note that Integer cache is not there for performance reasons, but rather to conform to the JLS, section 5.1.7; object identity must be given for values -128 to 127 inclusive.

Integer#valueOf(int) also documents this behavior:

this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.


Autoboxing caches -128 to 127. This is specified in the JLS (5.1.7).

If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

A simple rule to remember when dealing with objects is - use .equals if you want to check if the two objects are "equal", use == when you want to see if they point to the same instance.


Using primitive data types, ints, would produce true in both cases, the expected output.

However, since you're using Integer objects the == operator has a different meaning.

In the context of objects, == checks to see if the variables refer to the same object reference.

To compare the value of the objects you should use the equals() method E.g.

 b2.equals(b1)

which will indicate whether b2 is less than b1, greater than, or equal to (check the API for details)


It is memory optimization in Java related.

To save on memory, Java 'reuses' all the wrapper objects whose values fall in the following ranges:

All Boolean values (true and false)

All Byte values

All Character values from \u0000 to \u007f (i.e. 0 to 127 in decimal)

All Short and Integer values from -128 to 127.


Have a look at the Integer.java, if the value is between -128 and 127, it will use the cached pool, so (Integer) 1 == (Integer) 1 while (Integer) 222 != (Integer) 222

 /**
 * Returns an {@code Integer} instance representing the specified
 * {@code int} value.  If a new {@code Integer} instance is not
 * required, this method should generally be used in preference to
 * the constructor {@link #Integer(int)}, as this method is likely
 * to yield significantly better space and time performance by
 * caching frequently requested values.
 *
 * This method will always cache values in the range -128 to 127,
 * inclusive, and may cache other values outside of this range.
 *
 * @param  i an {@code int} value.
 * @return an {@code Integer} instance representing {@code i}.
 * @since  1.5
 */
public static Integer valueOf(int i) {
    assert IntegerCache.high >= 127;
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}       

Other answers describe why the observed effects can be observed, but that's really beside the point for programmers (interesting, certainly, but something you should forget all about when writing actual code).

To compare Integer objects for equality, use the equals method.

Do not attempt to compare Integer objects for equality by using the identity operator, ==.

It may happen that some equal values are identical objects, but this is not something that should generally be relied on.