What is Autoboxing?
Java automatically converts primitives to their wrapper classes when an object is required. This is called autoboxing.
// What you write:
arr[0] = 10;
// What Java does:
arr[0] = Integer.valueOf(10);
When Autoboxing Happens
β
Autoboxing occurs:
Integer x = 10; // int β Integer
Object[] arr = new Object[3];
arr[0] = 10; // int β Integer
list.add(10); // int β Integer (ArrayList)
β No autoboxing:
int a = 10; // stays primitive
int b = a + 5; // primitive arithmetic
void method(int x) {} // primitive parameter
Autoboxing with Object[] β
Object[] arr = new Object[3];
arr[0] = 10; // β
int β Integer, works!
arr[1] = 3.14f; // β
float β Float, works!
arr[2] = true; // β
boolean β Boolean, works!
Works because Integer, Float, Boolean all extend Object.
Autoboxing with Typed Arrays β
TestingClass[] arr = new TestingClass[3];
arr[0] = 10; // β ERROR!
// Java tries: arr[0] = Integer.valueOf(10);
// But Integer is NOT a TestingClass!
Critical: Even though 10 gets autoboxed to Integer, the type check still applies! Integer is not related to TestingClass, so it fails.
Wrapper Classes Map
| int | Integer |
| float | Float |
| double | Double |
| char | Character |
| boolean | Boolean |
| byte | Byte |
| short | Short |
| long | Long |
Golden Rule: Autoboxing converts primitives to wrappers, but it does NOT bypass array type safety checks!