AP CSA Unit 1 Day 20: Wrapper Equals Trap
Share
Wrapper Classes and == vs equals()
Section 1.12 — Wrapper Classes
Key Concept
Java constructors have special rules that distinguish them from regular methods. A constructor has no return type (not even void) and must have the same name as the class. Constructors can call other constructors using this(arguments) as the first statement. The AP exam tests constructor behavior with default values: if a parameter is not provided, the constructor may assign default values to instance variables. Constructor overloading allows a class to provide multiple ways to initialize an object with different starting states.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (B) false true true
Three different ways to compare Integer objects:
test1 (==): Compares references. new Integer(100) creates two separate objects, so a == b is false.
test2 (.equals()): Compares values. Both hold 100, so a.equals(b) is true.
test3 (.intValue() ==): Extracts the primitive int from each, then compares with ==. 100 == 100 is true because primitives compare by value.
Why Not the Others?
(A) Two objects created with new are always different references. == compares references for objects, not values.
(C) .equals() for Integer compares the numeric values, not the references. Since both contain 100, it returns true.
(D) intValue() returns a primitive int. Comparing primitives with == compares actual values, so 100 == 100 is true.
Common Mistake
The == operator behaves differently for objects vs primitives. For objects, it compares references. For primitives, it compares values. intValue() extracts the primitive, making == safe to use for value comparison.
AP Exam Tip
To safely compare Integer values, use .equals() or extract with .intValue(). Using == on Integer objects is unreliable and is a favorite AP exam trap.