Fundamentals 7 min read

Understanding Integer and String Comparison in Java

This article explains Java's Integer and String comparison quirks, detailing how autoboxing caches values between -128 and 127, why '==' behaves differently for objects versus primitives, and demonstrates these concepts with clear code examples and explanations.

Java Captain
Java Captain
Java Captain
Understanding Integer and String Comparison in Java

Lack of technical depth is common among many programmers, but senior engineers are expected to have depth; companies prefer engineers who can demonstrate solid understanding of core language mechanics.

Integer Comparison

Consider the following code that compares two Integer objects:

public static void main(String[] args) {
    Integer a = 128, b = 128;
    Integer c = 127, d = 127;
    System.out.println(a == b);
    System.out.println(c == d);
}

The output is false for a == b and true for c == d . This is because Java caches Integer objects whose values are between -128 and 127.

When an int value is assigned to an Integer, the static method Integer.valueOf is invoked, which uses an internal cache ( IntegerCache ) to return pre‑created objects for values in the cached range.

/**
 * Cache to support the object identity semantics of autoboxing for values between
 * -128 and 127 (inclusive) as required by JLS.
 */
private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer cache[];
    static {
        int h = 127;
        String integerCacheHighPropValue = sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            int i = parseInt(integerCacheHighPropValue);
            i = Math.max(i, 127);
            h = Math.min(i, Integer.MAX_VALUE - (-low) - 1);
        }
        high = h;
        cache = new Integer[(high - low) + 1];
        int j = low;
        for (int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);
    }
    private IntegerCache() {}
}
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);
}

Thus, values within the cache range are shared, leading to a == b being false (both 128, outside the cache) and c == d being true (both 127, inside the cache).

String Comparison

The next example demonstrates how string literals are handled:

public static void main(String[] args) {
    String s1 = "abc";
    String s2 = "abc";
    String s3 = new String("abc");
    System.out.println(s1 == s2);
    System.out.println(s1 == s3);
}

The output is true for s1 == s2 because both references point to the same interned string in the constant pool, while s1 == s3 is false because s3 is a distinct object created with new .

Integer vs int Comparison

public static void main(String[] args) {
    Integer a = new Integer(128);
    int b = 128;
    Integer c = new Integer(6);
    Integer d = new Integer(6);
    System.out.println(a == b);
    System.out.println(c == d);
}

Here, a == b evaluates to true because the Integer is unboxed to an int before comparison. In contrast, c == d is false because both are distinct Integer objects created with new , bypassing the cache.

For daily Java technical sharing, follow the Java group (WeChat ID: javatuanzhang) and scan the QR code provided.

JavacachingstringautoboxingObject ComparisonInteger
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.