Java has eight primitive types, such as int, double and boolean, which are fast but are not objects. Each one has a matching wrapper class: Integer, Double, Boolean and so on. Wrappers let numbers live in collections like ArrayList, carry useful methods such as Integer.parseInt, and can be null. Java converts between the two automatically, which is called autoboxing and unboxing. This lesson shows how that works and the traps it hides.
In this lesson you will learn
- The eight wrapper classes and why they exist
- Autoboxing and unboxing
- Parsing strings and other helper methods
- Why
==on wrappers gives surprising results - Null unboxing and performance traps
This lesson builds on Java variables and data types and ArrayList.
Boxing, Unboxing and Helper Methods
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Primitives cannot go into collections, wrappers can
List<Integer> marks = new ArrayList<>();
marks.add(88); // autoboxing: int -> Integer
marks.add(92);
int first = marks.get(0); // unboxing: Integer -> int
System.out.println(marks + " first=" + first);
// Parsing text and converting back
int age = Integer.parseInt("21");
double cgpa = Double.parseDouble("3.75");
String bin = Integer.toBinaryString(10);
System.out.println(age + 1 + " " + cgpa + " " + bin + " " + Integer.parseInt("1010", 2));
// Useful constants and helpers
System.out.println(Integer.MAX_VALUE + " " + Integer.MIN_VALUE);
System.out.println(Character.isDigit('7') + " " + Character.toUpperCase('b')
+ " " + Boolean.parseBoolean("TRUE"));
System.out.println(Integer.compare(5, 9) + " " + Integer.sum(5, 9) + " " + Double.isNaN(0.0 / 0.0));
}
}
Output
[88, 92] first=88
22 3.75 1010 10
2147483647 -2147483648
true B true
-1 14 true
- Collections hold objects, so
List<int>is not allowed.marks.add(88)works because Java autoboxes theintinto anInteger, andint first = marks.get(0)unboxes it back. Integer.parseIntandDouble.parseDoubleturn text into numbers, which you need for user input and files.parseInt("1010", 2)reads a binary number.age + 1 + " "printed 22 because Java adds the two numbers before it reaches the string.Integer.MAX_VALUEandMIN_VALUEgive the limits of anint.Characterhas tests such asisDigitandisLetter;Boolean.parseBooleanignores case.Integer.compare(5, 9)returns a negative number, which is what sorting code expects.0.0 / 0.0is “not a number”, detected withDouble.isNaN.
Four Wrapper Traps
public class Main {
public static void main(String[] args) {
Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println("a == b: " + (a == b)); // cached small values
System.out.println("c == d: " + (c == d)); // different objects
System.out.println("c.equals(d): " + c.equals(d)); // compares values
Integer bonus = null; // wrappers can be null
try {
int total = 1000 + bonus; // unboxing null
System.out.println(total);
} catch (NullPointerException e) {
System.out.println("NullPointerException when unboxing null");
}
try {
Integer.parseInt("12a");
} catch (NumberFormatException e) {
System.out.println("NumberFormatException: " + e.getMessage());
}
Long sumBoxed = 0L;
for (int i = 0; i < 1_000_000; i++) sumBoxed += i; // creates many objects
long sumPrim = 0;
for (int i = 0; i < 1_000_000; i++) sumPrim += i;
System.out.println(sumBoxed.equals(sumPrim) + " (same result either way)");
}
}
Output
a == b: true
c == d: false
c.equals(d): true
NullPointerException when unboxing null
NumberFormatException: For input string: "12a"
true (same result either way)
- Comparing with
==: for objects,==checks whether two references point to the same object. Java cachesIntegerobjects from -128 to 127, so127 == 127happens to be true, but128 == 128is false. Always compare wrapper values withequals(), or unbox tointfirst. - Unboxing
null: a wrapper can benull, meaning “no value”. Using it in arithmetic forces unboxing and throws aNullPointerException. - Parsing bad text throws
NumberFormatException, so wrap user input intry/catch. - Hidden objects in loops:
Long sumBoxedcreates a newLongobject on every addition. The result is the same, but a primitivelongis much faster and uses less memory.
Primitive Types and Their Wrappers
| Primitive | Wrapper | Parse method |
|---|---|---|
byte | Byte | Byte.parseByte |
short | Short | Short.parseShort |
int | Integer | Integer.parseInt |
long | Long | Long.parseLong |
float | Float | Float.parseFloat |
double | Double | Double.parseDouble |
char | Character | (use s.charAt(0)) |
boolean | Boolean | Boolean.parseBoolean |
parseInt returns a primitive int; Integer.valueOf returns an Integer object and uses the cache. Wrapper objects are immutable: count++ on an Integer creates a new object.
Common Mistakes
- Using
==to compareIntegerorLongvalues, which works in testing with small numbers and fails later with large ones. - Returning
nullfrom a method declared to returnInteger, then assigning it to anint. - Using wrapper types for counters and loop variables when a primitive would do.
- Calling
map.get(key)into anint; it returnsnullfor missing keys. UsegetOrDefault.
Practice Exercises
Exercise 1. Convert the strings "15", "x7" and "42" to numbers and print their sum, skipping invalid ones.
Show answer
int sum = 0;
for (String s : new String[] {"15", "x7", "42"}) {
try {
sum += Integer.parseInt(s);
} catch (NumberFormatException e) {
System.out.println("skipped " + s);
}
}
System.out.println(sum); // 57
Exercise 2. What does this print? Integer x = 1000, y = 1000; System.out.println(x.equals(y) + " " + (x.intValue() == y));
Show answer
true true. equals compares values, and when one side of == is a primitive, Java unboxes the other side and compares numbers.
Frequently Asked Questions
Should I use int or Integer?
Use int by default: it is faster and can never be null. Use Integer when you need an object, such as in collections and generics, or when “no value” (null) has a real meaning.
Can I change the Integer cache range?
The upper limit can be raised with a JVM option, but code should never depend on it. Compare values with equals() and the cache does not matter.
Summary
- Each primitive has a wrapper class so it can be used as an object.
- Autoboxing and unboxing convert between them automatically.
- Compare wrappers with
equals(), never==. - Unboxing
nullthrows an exception; prefer primitives in calculations.
