A wrapper class in Java is a class in the java.lang package that encapsulates a primitive data type inside an object. Java provides eight wrapper classes — Integer, Long, Double, Float, Short, Byte, Character and Boolean — enabling primitives to work with Collections, generics and any API that requires an object reference.
- Key Takeaway 1: Every Java primitive has a corresponding wrapper class in the
java.langpackage. - Key Takeaway 2: Autoboxing converts a primitive to its wrapper automatically; unboxing does the reverse.
- Key Takeaway 3: Collections like
ArrayListandHashMapwork only with objects, so wrapper classes are essential whenever you store primitives in them. - Key Takeaway 4: Wrapper classes provide utility methods such as
Integer.parseInt()andDouble.toString()that primitives alone cannot offer. - Key Takeaway 5: Unnecessary autoboxing inside loops is a common performance mistake; prefer primitives in tight loops when you do not need object features.
Why Wrapper Classes Exist
Java is an object-oriented language, but its eight primitive types are not objects. That design choice was made for raw performance, since primitives sit on the stack and avoid heap allocation overhead. The trade-off is that primitives cannot be used anywhere Java expects an Object.
The most practical place this limitation shows up is in the Collections Framework. An ArrayList<int> is simply illegal in Java. You need ArrayList<Integer> instead. That is the core reason wrapper classes in Java exist: to give primitives a full object identity so they can participate in generics, data structures and APIs built around Object.
There is a second reason that is equally important in real projects: utility methods. Integer.parseInt("42") converts a String to an int, and Integer.MAX_VALUE gives you the largest possible 32-bit integer without any magic number in your code. These are static methods on the wrapper class itself, not on the primitive. You will use them constantly when parsing user input or API responses.
If you are building on fundamentals and want to know which tools to set up before writing your first Java project, check out this guide on software development tools to learn first.
Primitives vs. Objects: the Core Trade-off
A primitive int stores a 4-byte value directly. An Integer object stores a reference to a heap-allocated object that internally holds that same 4-byte value, plus object overhead. According to Oracle’s official Java SE documentation, autoboxing was introduced in Java 5 specifically to reduce the manual conversion code developers had to write every time they moved between the two worlds. On a 64-bit HotSpot JVM, a single Integer object carries a 12-16 byte object header in addition to its 4-byte payload, as documented in the OpenJDK object layout specification, meaning it consumes roughly four times the memory of a plain int.
The practical cost is memory and speed. That difference is trivial for one variable but adds up fast when you are holding millions of values in a collection. Understanding this trade-off is exactly the kind of thing that comes up in backend Java interviews at companies like Infosys, TCS and Wipro, which collectively employ hundreds of thousands of Java developers across India according to NASSCOM’s annual IT workforce report.
The Eight Wrapper Classes
Java has exactly eight primitive types, and each one maps to a wrapper class in Java within the java.lang package. The table below covers all eight, their default values and the most commonly used utility method for each.
| Primitive Type | Wrapper Class | Default Value | Common Utility Method |
|---|---|---|---|
| byte | Byte | 0 | Byte.parseByte(String) |
| short | Short | 0 | Short.parseShort(String) |
| int | Integer | 0 | Integer.parseInt(String) |
| long | Long | 0L | Long.parseLong(String) |
| float | Float | 0.0f | Float.parseFloat(String) |
| double | Double | 0.0d | Double.parseDouble(String) |
| char | Character | ‘\u0000’ | Character.isDigit(char) |
| boolean | Boolean | false | Boolean.parseBoolean(String) |
All eight wrapper classes are immutable and final. Once an Integer object is created with the value 5, that value cannot change. If you do Integer x = 5; x = x + 1;, Java creates a brand-new Integer object holding 6 and points x at it. The original object is discarded. This is a common source of confusion for beginners.
int vs. Integer: the Difference That Matters
An int can never be null. An Integer can. This sounds minor, but it has real consequences. If a database column returns a missing value and you try to unbox a null Integer into an int, Java throws a NullPointerException at runtime. This is one of the most common wrapper-related bugs in production Java code, and it is exactly why understanding the difference between int and Integer matters before you write data-layer code.
The Stack Overflow Developer Survey 2024 reported that Java remains one of the top five most-used programming languages globally, with strong adoption in enterprise backends and Android development. Most of that enterprise code touches Collections and therefore wrapper classes in Java every single day.
Using valueOf and parseInt
Integer.valueOf(42) returns a cached Integer object for values between -128 and 127 (per the Java Language Specification, section 5.1.7). new Integer(42) always creates a fresh heap object and has been deprecated since Java 9. Use valueOf when you want the cached version, and parseInt when you just want a primitive back from a String.
A practical example: if your app reads a student’s roll number from a form field as a String, you would write int rollNo = Integer.parseInt(request.getParameter("roll"));. If the string is "abc", Java throws a NumberFormatException. Always validate input before parsing. For a deeper look at handling these runtime errors, see the 3.0 University guide on Java exceptions and common runtime errors.
Autoboxing and Unboxing in Java with Examples
Autoboxing is the automatic conversion Java performs when you assign a primitive to its corresponding wrapper type. Unboxing is the reverse: Java automatically extracts the primitive value from the wrapper when the context requires it. Both were introduced in Java 5 and are handled entirely by the compiler.
How Autoboxing Works
When you write Integer score = 95;, the compiler silently rewrites it as Integer score = Integer.valueOf(95);. You do not see the conversion, but it is happening. This is autoboxing in Java with an example you can verify by decompiling the bytecode with javap -c.
Unboxing works the same way in reverse. If you write int marks = score; where score is an Integer, the compiler rewrites it as int marks = score.intValue();. Clean, readable code, but there is a hidden method call happening underneath.
Here is a complete autoboxing and unboxing example in Java:
import java.util.ArrayList;
import java.util.List;
public class WrapperDemo {
public static void main(String[] args) {
// Autoboxing: int primitive -> Integer object
Integer score = 95;
// Unboxing: Integer object -> int primitive
int marks = score;
// Wrapper class in Java used with ArrayList
List<Integer> gradeList = new ArrayList<>();
gradeList.add(85); // autoboxing
gradeList.add(90);
int first = gradeList.get(0); // unboxing
System.out.println("First grade: " + first);
// Utility method
int parsed = Integer.parseInt("42");
System.out.println("Parsed value: " + parsed);
}
}
// Output:
// First grade: 85
// Parsed value: 42
The Performance Trap in Loops
Here is a mistake that shows up in real code reviews. Suppose you write a loop like this:
Long total = 0L;
for (long i = 0; i < 1_000_000; i++) {
total += i;
}
Because total is declared as Long (the wrapper), every iteration triggers an unboxing of total, an addition, and then an autoboxing of the result back into a new Long object. That is one million unnecessary object allocations. Declaring total as a primitive long instead eliminates the problem entirely. This is the kind of practical insight that separates a junior Java developer from a mid-level one.
According to the TIOBE Index (May 2025), Java consistently ranks in the top three programming languages worldwide, meaning a huge volume of production code is written in Java and autoboxing performance bugs in that code have real consequences at scale.
Autoboxing with Boolean and Character
Boolean and Character follow the same rules. Boolean flag = true; boxes the primitive true into a Boolean object. Because Boolean only has two possible values, the JVM caches both Boolean.TRUE and Boolean.FALSE, so autoboxed booleans do not create new objects. Character caches values from \u0000 to \u007F, covering the full ASCII range.
Wrapper Classes in Collections
This is where the wrapper class in Java earns its place in everyday programming. Java’s Collections Framework, which includes ArrayList, HashMap, HashSet and LinkedList, is built entirely around objects. Generics like List<T> require T to be a reference type, not a primitive.
A Concrete Java Wrapper Class Example with ArrayList
Say you are building a student grade tracker. You want to store a list of integer marks. You would write List<Integer> marks = new ArrayList<>(); and then marks.add(85);. The literal 85 is a primitive, but autoboxing converts it to Integer.valueOf(85) before it enters the list. When you retrieve it with int first = marks.get(0);, unboxing brings it back to a primitive.
The same pattern applies to HashMap<String, Integer> for storing name-to-score mappings, a structure used constantly in competitive programming and backend development across Indian IT firms.
Sorting and Comparing with Wrapper Classes
Wrapper classes implement Comparable, which means you can sort a List<Integer> with Collections.sort(marks) without writing any comparator. Integer.compare(a, b) is the recommended way to compare two integers in a custom comparator because it avoids the subtle overflow bug that appears when you subtract one int from another.
Students preparing for GATE CS or campus placements at Indian IT firms will encounter this in algorithm questions regularly. If you are deciding which computing degree best prepares you for this kind of role, the 3.0 University overview of BSc Computer Science subjects and scope is worth reading. MCA graduates heading into Java backend roles will find a salary and career breakdown in this piece on jobs and salary after MCA.
Null Handling in Collections
Because wrapper classes are objects, a List<Integer> can hold null entries. A int[] array cannot. This matters when you are reading data from a database or a CSV where some values might be absent. Using Integer lets you represent “no value” explicitly with null, while a primitive int would force you to use a sentinel value like -1, which is error-prone.
If you are coming from C and want to compare how primitives and memory work in a lower-level language, the 3.0 University tutorial on how to write, compile and run a C program gives useful contrast. For a broader perspective on how Java fits into different developer roles, see the comparison of full stack developer vs software developer.
Frequently Asked Questions
What is a wrapper class in Java?
A wrapper class in Java is a class in the java.lang package that encapsulates a primitive data type inside an object. For example, Integer wraps int and Boolean wraps boolean. This lets primitives be used wherever Java requires an object, such as in Collections or generic methods.
Why do we use wrapper classes in Java?
Wrapper classes in Java are used primarily because the Collections Framework only works with objects, not primitives. They also provide utility methods like Integer.parseInt() for type conversion, constants like Integer.MAX_VALUE, and the ability to store null to represent a missing value, which a primitive cannot do.
What is autoboxing and unboxing in Java?
Autoboxing is the automatic conversion of a primitive type to its corresponding wrapper class object, performed by the Java compiler at compile time. For example, writing Integer x = 10; triggers autoboxing: the compiler inserts Integer.valueOf(10) for you. Unboxing is the reverse process, converting a wrapper object back to its primitive using a method like intValue().
Which are the primitive wrapper classes in Java?
Java has eight primitive wrapper classes, all in the java.lang package: Byte, Short, Integer, Long, Float, Double, Character and Boolean. Each corresponds to one of Java’s eight primitive types. All eight are immutable and final, meaning their values cannot be changed after creation.
What is the difference between int and Integer in Java?
int is a primitive type that stores a 4-byte value directly on the stack and cannot be null. Integer is an object that lives on the heap, can hold null, and carries utility methods. The key practical difference is that unboxing a null Integer throws a NullPointerException, a bug that does not exist with plain int.
Are wrapper classes used in Java interviews at Indian IT companies?
Yes. Autoboxing, unboxing, the difference between int and Integer, and NullPointerException from null unboxing are standard topics in Java backend interviews at Infosys, TCS, Wipro, HCL and Cognizant. GATE CS also tests Collections and generics, where wrapper class knowledge is directly applied.
Where to go from here: Wrapper classes are one of those fundamentals that keep appearing throughout your Java career, from your first data structures assignment to production-grade backend services. The concepts are simple, but the edge cases around null, caching and autoboxing performance are exactly what interviewers test. Here are three concrete next steps for this week.
- Write a small Java program that stores student names and marks in a
HashMap<String, Integer>, then sorts entries by value usingInteger.compare(). It will make autoboxing and unboxing feel concrete rather than abstract. - Read the official Oracle Java 21 documentation for the Integer class to see the full list of utility methods and the caching specification. It is short and authoritative.
- Explore the 3.0 University online certification courses to build skills in areas where strong Java fundamentals pay off directly. If you are interested in security, solid programming knowledge is the foundation for ethical hacking and secure coding. The CEH v13 AI online course is a practical next step for developers who want to move into cybersecurity without starting from scratch.
Last updated: June 2025. Reviewed by the 3University editorial team.