1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Autoboxing And Unboxing
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
08Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Autoboxing And Unboxing

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
08Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Autoboxing & Unboxing

Overview

Before Java 5, converting between primitives and their Wrapper classes required verbose, manual code: Integer boxed = Integer.valueOf(5); and int unboxed = boxed.intValue();. This was tedious boilerplate that cluttered every codebase that used collections.

Autoboxing is the Java compiler automatically converting a primitive into its corresponding Wrapper Class when an Object is required. Unboxing is the reverse — the compiler automatically extracting the primitive value from a Wrapper Class when a primitive is required. This all happens invisibly at compile time; the compiler inserts the conversion calls for you.

While convenient, Autoboxing/Unboxing are not free. Each conversion creates a new Wrapper object (or calls a method to extract a value), which has heap allocation costs and garbage collection implications. Understanding when implicit conversions occur is critical for writing high-performance Java.

Syntax

Automatic Conversion in Practice
java
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // --- AUTOBOXING (primitive → Object) ---
        
        // Without Autoboxing (Old Java way):
        // Integer a = Integer.valueOf(42);
        
        // With Autoboxing (Modern Java — compiler does it for you):
        Integer a = 42;  // int 42 is automatically boxed to Integer
        
        // Autoboxing in Collections (Most common use!)
        List<Integer> numbers = new ArrayList<>();
        numbers.add(10); // int 10 is autoboxed to Integer(10) automatically
        numbers.add(20);
        
        // --- UNBOXING (Object → primitive) ---
        
        // Compiler inserts .intValue() call automatically:
        int sum = numbers.get(0) + numbers.get(1); // Unboxed to int for math
        System.out.println("Sum: " + sum); // 30
        
        // Unboxing in arithmetic
        Integer x = 100;
        Integer y = 200;
        int result = x + y; // Both are unboxed to int, added, stays as int
    }
}

Common Pitfalls

  • Triggering NullPointerException via unboxing. If you have Integer value = null; and then do int x = value;, the compiler inserts a .intValue() call, which is called on null, causing a NullPointerException. This is an extremely sneaky bug because there is no visible method call in your source code.
  • Performance degradation in inner loops. If your loop runs 100 million times and the loop variable is Integer instead of int, the JVM does 100 million autoboxing/unboxing operations. Each creates a heap allocation (or hits the cache for values -128 to 127). Always use primitives in performance-critical loops.
  • Ambiguous method resolution. If a method is overloaded with both process(int x) and process(Integer x), Java's autoboxing rules can cause surprising behavior when deciding which overload to call.

Interview Questions

What code does the Java compiler insert for Integer i = 5;?

The compiler transforms it into Integer i = Integer.valueOf(5);. For values in the range -128 to 127, valueOf() returns a cached Integer object (no new allocation). For values outside this range, it creates a new Integer object on the heap.

Can Autoboxing cause unexpected NullPointerExceptions and how?

Yes, and it is one of the most surprising bugs in Java. If Integer x = null; and you write int y = x;, the compiler inserts x.intValue(), which is a method call on a null object, throwing NullPointerException. The danger is that there is no visible method call in the source code, making the stack trace confusing.

Real-World Example

Stream pipelines on large datasets are a prime area where autoboxing causes hidden performance bottlenecks. IntStream avoids boxing/unboxing entirely for numeric processing, while Stream<Integer> creates Integer objects for every element.

example
java
// Slow path: Stream<Integer> boxes every int to Integer object
long countSlow = list.stream()
    .filter(n -> n > 100) // n is autoboxed Integer here
    .count();

// Fast path: IntStream avoids boxing entirely!
long countFast = list.stream()
    .mapToInt(Integer::intValue) // Unbox once, work with raw ints
    .filter(n -> n > 100)       // n is now a primitive int
    .count();

Check Your Knowledge

Test your understanding of Autoboxing & Unboxing with these quick questions.

Question 1

What is Autoboxing?

Question 2

Which code snippet will cause a NullPointerException due to Unboxing?

Question 3

For which range of integer values does Java cache Autoboxed Integer objects to avoid heap allocation?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Autoboxing & Unboxing

Overview

Before Java 5, converting between primitives and their Wrapper classes required verbose, manual code: Integer boxed = Integer.valueOf(5); and int unboxed = boxed.intValue();. This was tedious boilerplate that cluttered every codebase that used collections.

Autoboxing is the Java compiler automatically converting a primitive into its corresponding Wrapper Class when an Object is required. Unboxing is the reverse — the compiler automatically extracting the primitive value from a Wrapper Class when a primitive is required. This all happens invisibly at compile time; the compiler inserts the conversion calls for you.

While convenient, Autoboxing/Unboxing are not free. Each conversion creates a new Wrapper object (or calls a method to extract a value), which has heap allocation costs and garbage collection implications. Understanding when implicit conversions occur is critical for writing high-performance Java.

Syntax

Automatic Conversion in Practice
java
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // --- AUTOBOXING (primitive → Object) ---
        
        // Without Autoboxing (Old Java way):
        // Integer a = Integer.valueOf(42);
        
        // With Autoboxing (Modern Java — compiler does it for you):
        Integer a = 42;  // int 42 is automatically boxed to Integer
        
        // Autoboxing in Collections (Most common use!)
        List<Integer> numbers = new ArrayList<>();
        numbers.add(10); // int 10 is autoboxed to Integer(10) automatically
        numbers.add(20);
        
        // --- UNBOXING (Object → primitive) ---
        
        // Compiler inserts .intValue() call automatically:
        int sum = numbers.get(0) + numbers.get(1); // Unboxed to int for math
        System.out.println("Sum: " + sum); // 30
        
        // Unboxing in arithmetic
        Integer x = 100;
        Integer y = 200;
        int result = x + y; // Both are unboxed to int, added, stays as int
    }
}

Common Pitfalls

  • Triggering NullPointerException via unboxing. If you have Integer value = null; and then do int x = value;, the compiler inserts a .intValue() call, which is called on null, causing a NullPointerException. This is an extremely sneaky bug because there is no visible method call in your source code.
  • Performance degradation in inner loops. If your loop runs 100 million times and the loop variable is Integer instead of int, the JVM does 100 million autoboxing/unboxing operations. Each creates a heap allocation (or hits the cache for values -128 to 127). Always use primitives in performance-critical loops.
  • Ambiguous method resolution. If a method is overloaded with both process(int x) and process(Integer x), Java's autoboxing rules can cause surprising behavior when deciding which overload to call.

Interview Questions

What code does the Java compiler insert for Integer i = 5;?

The compiler transforms it into Integer i = Integer.valueOf(5);. For values in the range -128 to 127, valueOf() returns a cached Integer object (no new allocation). For values outside this range, it creates a new Integer object on the heap.

Can Autoboxing cause unexpected NullPointerExceptions and how?

Yes, and it is one of the most surprising bugs in Java. If Integer x = null; and you write int y = x;, the compiler inserts x.intValue(), which is a method call on a null object, throwing NullPointerException. The danger is that there is no visible method call in the source code, making the stack trace confusing.

Real-World Example

Stream pipelines on large datasets are a prime area where autoboxing causes hidden performance bottlenecks. IntStream avoids boxing/unboxing entirely for numeric processing, while Stream<Integer> creates Integer objects for every element.

example
java
// Slow path: Stream<Integer> boxes every int to Integer object
long countSlow = list.stream()
    .filter(n -> n > 100) // n is autoboxed Integer here
    .count();

// Fast path: IntStream avoids boxing entirely!
long countFast = list.stream()
    .mapToInt(Integer::intValue) // Unbox once, work with raw ints
    .filter(n -> n > 100)       // n is now a primitive int
    .count();

Check Your Knowledge

Test your understanding of Autoboxing & Unboxing with these quick questions.

Question 1

What is Autoboxing?

Question 2

Which code snippet will cause a NullPointerException due to Unboxing?

Question 3

For which range of integer values does Java cache Autoboxed Integer objects to avoid heap allocation?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A