Beginner · Arrays and strings · topic 15 of 60 · 25 min
Wrapper classes and autoboxing
Explanation
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.
| Primitive | Wrapper | Useful members |
|---|---|---|
| int | Integer | parseInt, valueOf, MAX_VALUE, MIN_VALUE, toBinaryString |
| long | Long | parseLong, MAX_VALUE |
| double | Double | parseDouble, isNaN, compare |
| char | Character | isDigit, isLetter, isUpperCase, toUpperCase |
| boolean | Boolean | parseBoolean |
| byte, short, float | Byte, Short, Float | parse… methods |
Autoboxing and unboxing
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 roundAutoboxing 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.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 fixTrap 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.
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)Character helpers
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')); // QNeed 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
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.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)
What does this print? Integer x = 100, y = 100; Integer p = 1000, q = 1000; System.out.println((x == y) + " " + (p == q));
Which line throws a NullPointerException? 1: Integer a = null; 2: Integer b = a; 3: int c = a; 4: System.out.println(b);
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Strings in depthArrays and strings · same module
- Two-dimensional arrays and array algorithmsArrays and strings · same module
- Structs, value types and reference typesC# and .NET · Classes and objects
- Values and typesJavaScript Programming (language in depth) · First steps: values, variables and operators
- Type conversion and castingC Programming (from zero to systems) · Operators and control flow
- Variables, types and constantsC++ Programming (modern C++ and DSA) · First steps: compiling, output, variables and input
Questions people ask about this
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.
How many primitive types does Java have?Related
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
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
- This is the last topic of “Arrays and strings”. The module exam comes next.
- Module 3 exam: Arrays and strings · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Classes and objects. 60 topics left in the course before the final exam.