๐งช Unit Test 004: Trap from Autoboxing โ
๐ Preface โ
Autoboxing in Java allows primitive values to be automatically wrapped into their object counterparts (e.g. int to Integer). While convenient, this feature can produce unexpected results, especially when comparing boxed primitives using ==.
๐ฌ Test Case โ
java
public class T_004_AutoboxingTrap {
@Test
public void test() {
Integer a = 100;
Integer b = 100;
Assertions.assertSame(a, b);
Integer x = 1000;
Integer y = 1000;
Assertions.assertNotSame(x, y);
}
}๐ Why This Matters โ
Java caches boxed integers from -128 to 127. Comparisons using == may appear to work for small numbers but fail for larger ones. Always use .equals() to compare object values. Misunderstanding this can cause bugs that only appear in edge cases or under specific conditions.