Can you provide an example where autoboxing could lead to unexpected behavior?

Autoboxing can sometimes produce unexpected results when wrapper objects are compared using the == operator. This happens because == compares object references, not object values, which may lead to incorrect assumptions about equality.

Key Points

Example

Two Integer objects containing the value 100 may return true when compared using == because they come from the Integer cache. However, two Integer objects containing 200 may return false because they are different objects.

public class Demo {

    public static void main(String[] args) {

        Integer a = 100;
        Integer b = 100;
        System.out.println(a == b); // true

        Integer x = 200;
        Integer y = 200;
        System.out.println(x == y); // false

        System.out.println(x.equals(y)); // true
    }
}

Interview Tip

A concise interview answer is

Autoboxing can lead to unexpected behavior when wrapper objects are compared using ==. Since == compares references rather than values, results may differ depending on JVM caching. Therefore, equals() should be used for comparing wrapper object values.

Last updated: 1 November 2026

Previous question: What is the difference between autoboxing and unboxing in Java?

Next question: Is there a scenario where autoboxing and unboxing could cause a NullPointerException?

More Core Java - Level II interview questions

All Core Java - Level II questions