Concept Flow - Unboxing
Start with Wrapper Object
Unboxing: Extract primitive value
Use primitive in expression or assignment
End
Unboxing converts a wrapper object to its primitive value automatically when needed.
Integer num = Integer.valueOf(10); int n = num; // unboxing System.out.println(n + 5);
| Step | Code Line | Action | Variable State | Output |
|---|---|---|---|---|
| 1 | Integer num = Integer.valueOf(10); | Create Integer object with value 10 | num = Integer(10) | |
| 2 | int n = num; | Unbox Integer to int | n = 10 | |
| 3 | System.out.println(n + 5); | Calculate 10 + 5 and print | 15 |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| num | null | Integer(10) | Integer(10) | Integer(10) |
| n | undefined | undefined | 10 | 10 |
Unboxing in Java: - Automatically converts wrapper objects (e.g., Integer) to primitives (e.g., int). - Happens when assigning or using wrapper in primitive context. - Syntax: int n = IntegerObject; - Beware: unboxing null causes NullPointerException. - Simplifies code by avoiding manual extraction.