Cosmic Module

J

Qubits of DPK

March 14, 2026

Core Java

Layman Explanation

Primitives are raw ingredients (flour, sugar). Wrapper classes are the same ingredients in a packaged box — same content but now comes with labels, instructions, and extra features (methods).

Primitive to Wrapper Mapping

javascript
QUBITS OF DPK
1PrimitiveWrapper
2────────────────────────
3int        →  Integer
4long       →  Long
5double     →  Double
6float      →  Float
7byte       →  Byte
8short      →  Short
9char       →  Character
10boolean    →  Boolean

Autoboxing & Unboxing

java
QUBITS OF DPK
1// Autoboxing — primitive → wrapper (automatic)
2Integer i = 5;          // int → Integer
3Double d = 3.14;        // double → Double
4Boolean b = true;       // boolean → Boolean
5
6// Unboxing — wrapper → primitive (automatic)
7int x = i;             // Integer → int
8double y = d;          // Double → double
9
10// Mixed arithmetic (auto unboxes)
11Integer a = 10;
12Integer b = 20;
13int sum = a + b;        // auto-unboxed, added as ints

Why Wrapper Classes Exist

java
QUBITS OF DPK
1// 1. Collections need Objects, not primitives
2ArrayList<int> list = new ArrayList<>();      // ❌
3ArrayList<Integer> list = new ArrayList<>();  // ✅
4
5// 2. Generics require Objects
6Map<String, Integer> map = new HashMap<>();   // ✅
7
8// 3. Null support
9Integer count = null;   // ✅ can be null
10int count = null;        // ❌ primitive can't be null
11// Useful for optional numeric fields in DB entities
12
13// 4. Utility methods
14Integer.parseInt("123")          // String → int
15Integer.toBinaryString(10)       // "1010"
16Integer.MAX_VALUE                // 2147483647
17Integer.MIN_VALUE                // -2147483648
18Double.parseDouble("3.14")
19Character.isDigit('5')           // true
20Character.toUpperCase('a')       // 'A'
21String.valueOf(42)               // "42"

Integer Cache — Famous Interview Trap

java
QUBITS OF DPK
1// Java caches Integer objects from -128 to 127
2Integer a = 127;
3Integer b = 127;
4System.out.println(a == b);   // true! Same cached object
5
6Integer x = 128;
7Integer y = 128;
8System.out.println(x == y);   // false! Different heap objects
9System.out.println(x.equals(y)); // true ✅ always use equals()!
Always use .equals() for wrapper comparison — never ==

NullPointerException with Unboxing

java
QUBITS OF DPK
1Integer count = null;
2int x = count;        // ❌ NullPointerException! Unboxing null
3
4// Fix:
5int x = (count != null) ? count : 0;
6// Or:
7int x = Objects.requireNonNullElse(count, 0);

Performance Note

java
QUBITS OF DPK
1// Wrapper is slower than primitive
2// Avoid in performance-critical loops
3
4// Bad:
5Long sum = 0L;
6for (long i = 0; i < 1000000; i++) {
7    sum += i;  // constant boxing/unboxing!
8}
9
10// Good:
11long sum = 0L;
12for (long i = 0; i < 1000000; i++) {
13    sum += i;  // primitive, fast
14}

Interview Answer (SDE-2)

"Wrapper classes wrap primitives as Objects to use them in contexts requiring objects — collections, generics, null assignment. Autoboxing automatically converts primitive to wrapper; unboxing converts back. Integer caches -128 to 127 so == works in that range but fails outside — always use equals() for wrapper comparison. Unboxing null throws NullPointerException — always null check first. Wrapper methods like Integer.parseInt(), Character.isDigit() are utility methods heavily used in DSA."

Interview Questions & MAANG-Level Answers

Q1. What is a wrapper class and why does it exist?
Wrapper classes (Integer, Double, Boolean etc.) wrap primitive values as objects. Why: (1) Collections require objects — ArrayList<Integer> not ArrayList<int>. (2) Generics require objects — Optional<Integer>, CompletableFuture<Integer>. (3) Null support — Integer can be null (useful for optional DB fields), int cannot. (4) Utility methods — Integer.parseInt(), Integer.toBinaryString(), Integer.MAX_VALUE, Character.isDigit().
Q2. What is autoboxing and unboxing?
Autoboxing: automatic conversion from primitive to wrapper: Integer i = 5 — Java inserts Integer.valueOf(5). Unboxing: automatic conversion from wrapper to primitive: int x = i — Java inserts i.intValue(). Happens in: assignments, method arguments, arithmetic operations with mixed types. Performance note: avoid in tight loops — each autobox creates a new object (except cached range). Long sum = 0L; for(long i=0; i<1M; i++) sum += i; — constant boxing degrades performance significantly.
Q3. Why does Integer 127 == 127 return true but 128 == 128 return false?
Java's IntegerCache caches Integer objects from -128 to 127. Integer.valueOf(127) always returns the same cached object, so == (reference comparison) is true. Integer.valueOf(128) creates a new object each time, so == compares different references — false. This is specified in the Java Language Specification. Always use .equals() for Integer comparison: a.equals(b) works correctly for ALL values.
Q4. What is the danger of unboxing a null wrapper?
NullPointerException! Unboxing a null wrapper automatically calls .intValue() on null:
java
QUBITS OF DPK
1Integer count = null;
2int x = count;  // throws NullPointerException!
3// Also dangerous in arithmetic:
4Integer a = null, b = 5;
5int sum = a + b;  // NPE when unboxing a!
Always null-check before unboxing: int x = (count != null) ? count : 0; or use Objects.requireNonNullElse(count, 0).
Q5. When would you use Integer instead of int for a field?
Use Integer (object) when: (1) The field can be absent/unknown — Integer age = null represents "age not provided". (2) Working with Collections or Generics. (3) JPA/Hibernate entity fields — Integer id allows null before persistence. (4) JSON deserialization where field may be missing. (5) Method return type where null means "not found". Use int (primitive) when: value always exists, performance-critical code, avoiding boxing overhead in calculations.