Skip to content

Beginner · Arrays and strings · topic 15 of 60 · 25 min

Wrapper classes and autoboxing

Explanation

Each primitive has a wrapper class (int → Integer, double → Double, char → Character, boolean → Boolean) so it can be used where an object is needed, such as in collections. Java converts automatically (autoboxing and unboxing). Watch two traps: unboxing a null throws NullPointerException, and == on Integer objects compares references (true for -128 to 127 because of a cache, false for 128).

Why wrapper classes?

Collections like ArrayList and HashMap can only hold objects, not primitives. List<int> does not compile. Wrapper classes are small objects that hold one primitive value, so you write List<Integer>. They also provide useful static methods and constants.

PrimitiveWrapperUseful members
intIntegerparseInt, valueOf, MAX_VALUE, MIN_VALUE, toBinaryString
longLongparseLong, MAX_VALUE
doubleDoubleparseDouble, isNaN, compare
charCharacterisDigit, isLetter, isUpperCase, toUpperCase
booleanBooleanparseBoolean
byte, short, floatByte, Short, Floatparse… methods

Autoboxing and unboxing

java
java.util.List<Integer> marks = new java.util.ArrayList<>();
marks.add(85);                 // autoboxing: int 85 → Integer
int first = marks.get(0);      // unboxing: Integer → int
Integer total = 0;
for (int m : marks) total += m;   // works, but boxes and unboxes every round

Autoboxing is convenient but not free: each box is an object. In performance-critical loops over millions of numbers, use primitive arrays or primitive streams (IntStream) instead of List<Integer>.

Trap 1: unboxing null

java
java.util.Map<String, Integer> stock = new java.util.HashMap<>();
Integer qty = stock.get("ghee");   // null: key not present
int n = qty;                        // NullPointerException while unboxing!
int safe = stock.getOrDefault("ghee", 0);   // the fix

Trap 2: == on wrapper objects

Integer.valueOf (used by autoboxing) caches Integer objects for values from -128 to 127. Two boxed values in that range are the same cached object, so == is true. Outside the range, each boxing usually creates a new object, so == is false even when the numbers are equal. Always compare wrappers with equals, or unbox to int first.

java
Integer a = 127, b = 127;
System.out.println(a == b);        // true  (cached object)
Integer c = 128, d = 128;
System.out.println(c == d);        // false (two different objects)
System.out.println(c.equals(d));   // true
System.out.println(c.intValue() == d);   // true (one side unboxed → numeric comparison)
Careful: This == trap appears in real bugs: code comparing order quantities or user ids works in testing with small numbers and fails in production with larger ones. Compare Integer, Long and other wrappers with equals (or Objects.equals(a, b) when either may be null).

Character helpers

java
char ch = '7';
System.out.println(Character.isDigit(ch));          // true
System.out.println(Character.getNumericValue(ch));  // 7
System.out.println(Character.isLetter('क'));        // true (Unicode letters work)
System.out.println(Character.toUpperCase('q'));     // Q
Think of it like this: A wrapper is like putting a coin (the primitive) into a small labelled envelope (the object) so it can go into a filing cabinet that only accepts envelopes (a collection). Two envelopes with the same coin are still two envelopes, which is why == can say "different".
Tip: Use primitives (int, double) by default, and wrappers only when an object is required (collections, generics, nullable values from databases).

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Wrapper classes and autoboxing · 1/6

Wrappers and autoboxing

In this lesson you will use wrapper classes, the object versions of primitives.

Prefer a video by a teacher? Find free videos on “java wrapper classes autoboxing integer cache 127 128” on YouTube ↗

In real life: Counting OTP attempts per user

A login service counts failed OTP attempts per phone number in a HashMap<String, Integer>. Reading a number that has never failed returns null, so the code uses getOrDefault to avoid a NullPointerException, and compares counts as ints.

java
java.util.Map<String, Integer> fails = new java.util.HashMap<>();
String phone = "9876543210";
fails.put(phone, fails.getOrDefault(phone, 0) + 1);
int count = fails.getOrDefault(phone, 0);
if (count >= 3) System.out.println("Blocked for 15 minutes");

Practice (0/3 done)

Task 1 · Question

What does this print? Integer x = 100, y = 100; Integer p = 1000, q = 1000; System.out.println((x == y) + " " + (p == q));

Task 2 · Question

Which line throws a NullPointerException? 1: Integer a = null; 2: Integer b = a; 3: int c = a; 4: System.out.println(b);

Task 3 · Practice

Write a program that reads words from a String array, counts how many times each appears in a HashMap<String, Integer> using getOrDefault, and prints only the words that appear more than once. Then show (with a comment) why comparing two counts with == could be a bug.

Quick quiz

Question 1

1.What is autoboxing?

Question 2

2.Which declaration does NOT compile?

Question 3

3.What range does the Integer cache cover by default?

Question 4

4.Character.isDigit('x') returns…

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What is autoboxing?

Answer: Automatic conversion from a primitive to its wrapper object

For example int → Integer.

Which declaration does NOT compile?

Answer: List<int> b;

Generics need object types.

What range does the Integer cache cover by default?

Answer: -128 to 127

Integer.valueOf caches -128 to 127.

Character.isDigit('x') returns…

Answer: false

x is a letter.

Assigning one class variable to another...Related

Answer: Copies the reference, so both refer to the same object

Classes are reference types.

From Structs, value types and reference types

How many primitive types does Java have?Related

Answer: 8

byte, short, int, long, float, double, char, boolean.

From Variables and primitive types

Which of these is NOT a primitive type?Related

Answer: array

Arrays are objects. The primitives are string, number, bigint, boolean, undefined, null and symbol.

From Values and types

In char a = 100, b = 100; int c = a + b; what is c?Related

Answer: 200

Promotion to int prevents overflow in the addition.

From Type conversion and casting

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. This is the last topic of “Arrays and strings”. The module exam comes next.
  2. Module 3 exam: Arrays and strings · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Classes and objects. 60 topics left in the course before the final exam.

← Previous: StringBuilder and formatting