These are the notes for Java episode 28. A teacher's register needs to say "Ravi was absent", but an int can never be empty, and soon we'll want lists of numbers, which don't accept an int at all. Today's fix: wrapper classes like Integer, which put a primitive value inside an object. We'll see what autoboxing and unboxing quietly write for you, and the three traps they hide: unboxing null, == on wrappers (the Integer cache), and slow loops. Every example was run with javac 21.
The problem: absent means zero?
Asha scored 78, Meena 91, and Ravi was absent. The column must hold a number, so the teacher writes 0:
public class Main {
public static void main(String[] args) {
int[] marks = { 78, 0, 91 }; // Ravi was absent
int total = 0;
for (int m : marks) total += m;
System.out.println("Class average: " + total / marks.length);
}
}
Class average: 56
The real average of the students who wrote the test is 84. Here 0 means two different things, scored zero and wasn't there, and the program can't tell them apart.
The obvious fix fails: int can't be null
public class Main {
public static void main(String[] args) {
int raviMarks = null;
}
}
Main.java:3: error: incompatible types: <null> cannot be converted to int
int raviMarks = null;
^
1 error
A primitive variable (episode 2) holds the value itself, so it always contains some number. Only a reference (episode 14), which points at an object, can point at nothing (null).
The fix: wrap the value in an object
| In real life | In Java |
|---|---|
| A loose roti: just food in your hand | int 78: a raw value (primitive) |
| A roti in a tiffin box, with a label and a lid | Integer 78: an object holding one int |
| No tiffin today: the hook is empty | Integer x = null: no object at all |
| A dabbawala only carries boxes | ArrayList<Integer>: collections hold objects |
A wrapper class is a class whose object holds exactly one primitive value. Every primitive has one:
| Primitive | Wrapper | Note |
|---|---|---|
byte |
Byte |
|
short |
Short |
|
int |
Integer |
full word |
long |
Long |
|
float |
Float |
|
double |
Double |
|
char |
Character |
full word |
boolean |
Boolean |
All of them live in java.lang, so no import is needed, and all of them are immutable: an Integer object never changes its value.
The register, fixed:
public class Main {
public static void main(String[] args) {
Integer[] marks = { 78, null, 91 };
int total = 0, present = 0;
for (Integer m : marks) {
if (m == null) continue;
total += m;
present++;
}
System.out.println("Class average: " + total / present);
}
}
Class average: 84
null now means absent, and 0 would mean scored zero.
Collections need objects
ArrayList (fully covered in episode 30) is a list that grows as you add. The type in the angle brackets says what it holds:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<int> marks = new ArrayList<>();
}
}
Main.java:5: error: unexpected type
ArrayList<int> marks = new ArrayList<>();
^
required: reference
found: int
1 error
Collections only hold objects, through references. Use the wrapper:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> marks = new ArrayList<>();
marks.add(78);
marks.add(91);
int first = marks.get(0);
System.out.println(marks + " first=" + first);
}
}
[78, 91] first=78
Autoboxing and unboxing
We put plain ints in and took a plain int out without writing any conversion. The compiler did it:
| You write | The compiler writes | Name |
|---|---|---|
marks.add(78); |
marks.add(Integer.valueOf(78)); |
autoboxing |
int first = marks.get(0); |
int first = marks.get(0).intValue(); |
unboxing |
Integer x = 5; |
Integer x = Integer.valueOf(5); |
autoboxing |
int y = x + 1; |
int y = x.intValue() + 1; |
unboxing |
- Boxing: primitive → wrapper object (
valueOf). Autoboxing = done automatically. - Unboxing: wrapper object → primitive (
intValue(),doubleValue(), ...). - Arithmetic (
+,<,++) on wrappers always unboxes first.
Convenient, but hidden code can hide bugs.
Trap 1: unboxing null
public class Main {
public static void main(String[] args) {
Integer raviMarks = null;
int m = raviMarks;
System.out.println(m);
}
}
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because "<local1>" is null
at Main.main(Main.java:4)
There's no intValue() in our code, yet the message says it was called: that's the hidden unboxing. (Compiled with javac -g, the message names the variable: because "raviMarks" is null.) The same happens with a map lookup that finds nothing:
HashMap<String, Integer> marks = new HashMap<>();
marks.put("Asha", 78);
int bad = marks.get("Ravi");
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.HashMap.get(Object)" is null
Fix: check for null before unboxing.
Trap 2: == and the Integer cache
public class Main {
public static void main(String[] args) {
Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println(a == b);
System.out.println(c == d);
System.out.println(c.equals(d));
}
}
true
false
true
- On objects,
==compares references (episode 22), not values. Integer.valueOfkeeps ready-made objects for every value from -128 to 127 (the Integer cache). Small values share one object, so the references happen to match.- 128 is outside the cache, so
canddare two different objects. Byte,Short,LongandCharacter(0-127) cache small values too;DoubleandFloatdon't.- Rule: compare wrappers with
.equals(), never==. (When one side is a primitive,c == 1000unboxescand compares values.)
The wrapper toolbox
public class Main {
public static void main(String[] args) {
int a = Integer.parseInt("42");
Integer b = Integer.valueOf("42");
double d = Double.parseDouble("99.5");
boolean ok = Boolean.parseBoolean("true");
System.out.println(a + " " + b + " " + d + " " + ok);
System.out.println(Integer.MAX_VALUE + " " + Integer.MIN_VALUE);
System.out.println(Integer.toBinaryString(10) + " " + Integer.toString(255, 16));
System.out.println(Character.isDigit('7') + " " + Character.toUpperCase('a'));
System.out.println(Integer.compare(5, 9) + " " + Integer.max(5, 9));
}
}
42 42 99.5 true
2147483647 -2147483648
1010 ff
true A
-1 9
| Method | Returns | Example |
|---|---|---|
Integer.parseInt(s) |
int |
parseInt("42") → 42 |
Integer.parseInt(s, radix) |
int in another base |
parseInt("1010", 2) → 10 |
Integer.valueOf(s) |
Integer (uses the cache) |
valueOf("42") |
Double.parseDouble(s) |
double |
"99.5" → 99.5 |
Integer.MAX_VALUE / MIN_VALUE |
the int limits | 2147483647 / -2147483648 |
Integer.toBinaryString(n) |
binary text | 10 → "1010" |
Integer.toString(n, radix) |
text in a base | 255, 16 → "ff" |
Character.isDigit(c) / isLetter(c) |
boolean |
'7' → true |
Character.toUpperCase(c) |
char |
'a' → 'A' |
Integer.compare(x, y) |
negative, 0, positive | compare(5, 9) → -1 |
Bad text still throws NumberFormatException (episode 26).
Trap 3: wrappers in a loop are slow
public class Main {
public static void main(String[] args) {
long t1 = System.nanoTime();
Long sum = 0L;
for (long i = 0; i < 50_000_000; i++) sum += i;
long t2 = System.nanoTime();
long sum2 = 0L;
for (long i = 0; i < 50_000_000; i++) sum2 += i;
long t3 = System.nanoTime();
System.out.println("Long: " + (t2 - t1) / 1_000_000 + " ms");
System.out.println("long: " + (t3 - t2) / 1_000_000 + " ms");
}
}
One run on our machine (times vary from run to run and machine to machine):
Long: 282 ms
long: 25 ms
Every sum += i on a Long unboxes, adds, and boxes a new Long object: millions of objects for nothing. Use primitives for calculations; use wrappers only when you need null or a collection.
Common mistakes (and the real error messages)
| Mistake | Real message | Why | Fix |
|---|---|---|---|
int raviMarks = null; |
error: incompatible types: <null> cannot be converted to int |
primitives can't be null | Integer raviMarks = null; |
ArrayList<int> |
error: unexpected type / required: reference / found: int |
collections hold objects | ArrayList<Integer> |
| Unboxing null | NullPointerException: Cannot invoke "java.lang.Integer.intValue()" |
hidden intValue() on null |
check != null first |
c == d with Integers above 127 |
no error: prints false |
== compares references |
c.equals(d) |
Integer.parseInt("four") |
NumberFormatException: For input string: "four" |
not a number | catch it (episode 26) |
list.remove(10) on an ArrayList<Integer> meant to remove the value 10 |
IndexOutOfBoundsException (or the wrong item removed) |
remove(int) removes by index |
list.remove(Integer.valueOf(10)) |
Long sum in a hot loop |
no error, just slow | a new object per step | use long |
Mini project: attendance-aware report card
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
String[] names = { "Asha", "Ravi", "Meena", "Kabir" };
Integer[] marks = { 78, null, 91, 0 }; // Ravi absent, Kabir scored 0
ArrayList<Integer> present = new ArrayList<>();
for (int i = 0; i < names.length; i++) {
if (marks[i] == null) {
System.out.println(names[i] + ": absent");
} else {
System.out.println(names[i] + ": " + marks[i]);
present.add(marks[i]);
}
}
int total = 0, best = Integer.MIN_VALUE;
for (int m : present) {
total += m;
best = Integer.max(best, m);
}
System.out.println("Wrote the test: " + present.size());
System.out.println("Average: " + (double) total / present.size());
System.out.println("Best: " + best);
}
}
Asha: 78
Ravi: absent
Meena: 91
Kabir: 0
Wrote the test: 3
Average: 56.333333333333336
Best: 91
Kabir's 0 counts (he wrote the test), Ravi's absence doesn't.
Practice
- Average
Integer[] { 60, null, 80, null, 100 }, skipping nulls. - Predict, then run:
Integer x = 127, y = 127; System.out.println(x == y); - Turn the binary text
"1010"into a number. - Count the digits in
"Room 204B"withCharacter.isDigit.
Solutions
1. Same loop as the register: skip null, divide by the number present.
Integer[] m = { 60, null, 80, null, 100 };
int total = 0, present = 0;
for (Integer x : m) { if (x == null) continue; total += x; present++; }
System.out.println("Average: " + total / present); // Average: 80
2. true, because 127 is inside the Integer cache, so both variables point to the same object. With 128 it would print false.
3. Integer.parseInt("1010", 2) gives 10.
4.
int digits = 0;
for (char c : "Room 204B".toCharArray()) if (Character.isDigit(c)) digits++;
System.out.println("Digits: " + digits); // Digits: 3
Quick quiz
Integer a = 100, b = 100;
Integer c = 1000, d = 1000;
int e = 1000;
System.out.println((a == b) + " " + (c == d) + " " + (c == e));
A) true true true B) true false false C) true false true D) false false true
Answer
C. 100 is cached, so a == b is true. 1000 is outside -128..127, two objects, so c == d is false. c == e compares with a primitive, so c is unboxed and the values are compared: true.
true false true
Interview questions
- What is a wrapper class? A class whose object holds one primitive value (
Integer,Double, ...), so the value can benull, used in collections and generics, and have methods. - What are autoboxing and unboxing? The compiler's automatic conversion between a primitive and its wrapper:
Integer.valueOf(x)for boxing,x.intValue()for unboxing. - Why does
Integer a = 128, b = 128; a == bprint false?==compares references;Integer.valueOfcaches only -128 to 127, so 128 creates two objects. Useequals. - What happens when you unbox null? A
NullPointerExceptionfrom the hiddenintValue()call. parseIntvsvalueOf?parseIntreturns a primitiveint;valueOfreturns anInteger(and reuses cached objects).- Why can't generics use primitives? Generic type parameters must be reference types (episode 29); primitives aren't objects.
- Are wrappers mutable? No. Every wrapper is immutable;
x++on anIntegercreates a new object. - When should you prefer primitives? For calculations and large arrays: they're faster and use less memory, and can't be null.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Primitive | One of the 8 basic value types, not an object | int, double, char |
| Reference | A variable that points to an object (or null) |
Integer x |
| null | "No object" | Integer raviMarks = null; |
| Wrapper class | A class whose object holds one primitive | Integer, Character |
| Boxing | Primitive → wrapper object | Integer.valueOf(78) |
| Unboxing | Wrapper object → primitive | x.intValue() |
| Autoboxing | Boxing done automatically by the compiler | marks.add(78) |
| Collection | An object that holds a group of objects | ArrayList<Integer> |
| ArrayList | A list that grows as you add (episode 30) | new ArrayList<>() |
Angle brackets <> |
The type a collection holds (generics, episode 29) | ArrayList<Integer> |
| Integer cache | Pre-made Integer objects for -128..127 |
Integer a = 127, b = 127; a == b is true |
| Immutable | Can't change after creation | every wrapper object |
| parseInt | Text → int |
Integer.parseInt("42") |
| valueOf | Text or int → Integer |
Integer.valueOf("42") |
| MAX_VALUE / MIN_VALUE | The largest / smallest value of a type | Integer.MAX_VALUE = 2147483647 |
| Radix | The base of a number system | 2 for binary, 16 for hex |
| NullPointerException | Using a null reference as an object | unboxing null |
| System.nanoTime() | A precise timer in nanoseconds, for measuring | t2 - t1 |
Summary
- A primitive always holds a value, so it can't be
null, and can't go into collections. - A wrapper class (
Integer,Character, ...) is an object holding one primitive; it can benulland can go intoArrayList<Integer>. - Autoboxing (
valueOf) and unboxing (intValue()) are written by the compiler for you. - Traps: unboxing null →
NullPointerException;==on wrappers compares references (cache -128..127): use.equals(); wrappers in loops are slow. - Wrappers carry helpers:
parseInt,valueOf,MAX_VALUE,toBinaryString,Character.isDigit. - Next: how does
ArrayListknow it holdsIntegers, and refuse anything else? Episode 29: generics.