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: • Autoboxing automatically converts primitive values into wrapper objects. • The == operator compares object references for wrapper classes, not their contents. • Integer objects in the range -128 to 127 are cached by the JVM, which can affect comparison results. • For values outside the cache range, separate objects may be created, causing == to return false. • Use equals() when comparing wrapper object values to avoid unexpected behavior.

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.

Code Example:

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."