Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Collections

Java Wrapper Classes and Autoboxing

List<int> won't compile because a list holds objects only. Integer.valueOf puts 87 in a box and intValue takes it out, and add and get do it for you. Then two traps: 128 == 128 is false, and unboxing a null Integer throws a NullPointerException.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Collections

What you will learn

  • Explain why a List can't hold an int and needs Integer
  • Box a value with valueOf and unbox it with intValue
  • Describe what the compiler writes for you when it autoboxes
  • Avoid the two wrapper traps: == past 127 and unboxing null

Before you start

  • Java primitive types and memory
  • From arrays to collections: the framework map

Think of a wrapper class as a gift box. A plain value goes into a box so it can sit on the shelf with the other objects. It's worth knowing before you use any collection.

A list takes objects only

List<String> names = new ArrayList<>();   // fine: String is an object
List<int> marks = new ArrayList<>();      // does not compile

The second line fails with unexpected type, required: reference, found: int. Only objects can go in a list, and an int is a plain value, a primitive type. That's the whole problem.

Into the box and back out

package org.studyeasy.s04l02;

public class Ex01_WrapperTypes {
    public static void main(String[] args) {
        int marks = 87;                          // a plain value
        Integer box = Integer.valueOf(marks);    // boxed: an object
        int back = box.intValue();               // unboxed

        Double price = Double.valueOf(19.99);    // double -> Double
        Boolean paid = Boolean.valueOf(true);    // boolean -> Boolean

        System.out.println("box   = " + box);
        System.out.println("back  = " + back);
        System.out.println("price = " + price);
        System.out.println("paid  = " + paid);
    }
}
box   = 87
back  = 87
price = 19.99
paid  = true

Integer.valueOf(marks) creates an Integer object on the heap with 87 inside: that's boxing. box.intValue() takes the value out again: unboxing. Every primitive has a wrapper class: double has Double, boolean has Boolean, and so on. A wrapper only takes its own kind, so Integer id = 5.5; doesn't compile.

Java boxes it for you

List<Integer> scores = new ArrayList<>();
scores.add(67);                 // int -> Integer, automatic
scores.add(87);
scores.add(92);

int first = scores.get(0);      // Integer -> int, automatic
int total = 0;
for (int score : scores) {      // unboxed on every pass
    total += score;
}
System.out.println("First: " + first);
System.out.println("Total: " + total);
First: 67
Total: 246

You pass a plain 67 to add, and Java wraps it in an Integer: autoboxing. get(0) hands back an Integer and Java unboxes it into first. The loop unboxes on every pass: 67 + 87 + 92 is 246. Behind the scenes, the compiler writes Integer.valueOf(67) and .intValue() for you; they're the same boxes as before. The list type still has to be List<Integer>.

Trap 1: == asks "the same object?"

Integer smallA = 127;
Integer smallB = 127;
System.out.println("127 == 127 : " + (smallA == smallB));

Integer bigA = 128;
Integer bigB = 128;
System.out.println("128 == 128 : " + (bigA == bigB));
System.out.println("equals     : " + bigA.equals(bigB));
127 == 127 : true
128 == 128 : false
equals     : true
Java keeps ready-made Integer objects from -128 to 127. smallA and smallB both point to the one cached 127 object, so == is true. bigA and bigB each get a new Integer object holding 128, two different objects, so == is false while equals compares the values and is true. cache: -128 to 127, shared smallAsmallB 127 bigAbigB 128128 == true: one object == false: two objects. equals: true
Inside the cache, == happens to work. Past 127, each box is a new object.

Java keeps ready-made Integer objects from -128 to 127, shared by everyone, so both 127s point to the same object. 128 is outside the cache, so each variable gets a brand new object, and == compares objects, not values. This bug hides quietly in real code. With wrappers, compare with equals (see equals and hashCode).

Trap 2: unboxing nothing

package org.studyeasy.s04l02;

public class Ex04_UnboxNull {
    static Integer findDiscount(String code) {
        if (code.equals("SAVE10")) {
            return 10;
        }
        return null;                    // no such code
    }

    public static void main(String[] args) {
        int ok = findDiscount("SAVE10");
        System.out.println("SAVE10 gives " + ok);

        Integer none = findDiscount("NONE");
        System.out.println("NONE gives " + none);

        try {
            int d = findDiscount("NONE");   // unboxing null
            System.out.println("d = " + d);
        } catch (NullPointerException e) {
            System.out.println("Crash: NullPointerException");
        }
    }
}
SAVE10 gives 10
NONE gives null
Crash: NullPointerException

An Integer can hold null, meaning no object at all, so printing it shows "null". But int d = ... makes the compiler add .intValue(), and there's no box to open. Java throws a NullPointerException; without the catch, the message says it cannot invoke Integer.intValue() because the return value of findDiscount is null. An Integer may be null; an int never is.

Recap

IdeaCode
BoxInteger.valueOf(87)
Unboxbox.intValue()
Autobox and unboxscores.add(67), int first = scores.get(0)
Compare wrappersa.equals(b), not a == b
Nullan Integer can be null; unboxing it throws

With that in place, on to the most used list of all: ArrayList.

Keep going in Java · 47 of 79

Previous
From Arrays to Collections: The Java Collections Framework Map
Next post
Java ArrayList: The Stretchy Array
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Java equals and hashCode: Why a HashSet Needs Both

== asks if it's the very same object, equals compares values, and hashCode puts equal objects in the same HashSet bucket. Three small programs show what breaks when hashCode is missing.

From Arrays to Collections: The Java Collections Framework Map

An array of 3 students can't seat John, so Java throws Index 3 out of bounds. A List just grows. Then the map of the framework: List, Set and Queue under Collection, Map beside it, four behaviours in one program, and why the variable type should be the interface.

Java ArrayList: The Stretchy Array

add, add at an index, get, set, remove and contains on a list of courses and a cart, why Git at index 1 pushes SQL and Spring right, removing scores below 50 with an Iterator or removeIf, List.of that can't change, and the array inside that grows from 10 to 15.

Java LinkedList vs ArrayList: Nodes or an Array

An ArrayList is one block of cells; a LinkedList is a chain of nodes with next and prev links. Orders ORD-101 to ORD-106 show addFirst, getLast, removeFirst and remove(1), why get(2) walks two hops, and why a front insert moves three values in one and changes two links in the other.

On this page

  • A list takes objects only
  • Into the box and back out
  • Java boxes it for you
  • Trap 1: == asks "the same object?"
  • Trap 2: unboxing nothing
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.