1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Wrapper Classes
45% OFFBLACK FRIDAY SALE
Sale ends in
02Days
13Hrs
13Mins
36Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Wrapper Classes

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

02Days
13Hrs
13Mins
36Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
    • Java + DSA
    • Full Stack Web Dev
    • AI/ML + Python
  • 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

Wrapper Classes

Overview

Java's Collections Framework (ArrayList, HashMap, HashSet) is built entirely using Generics. Generics require types to be Objects, not primitives. You cannot write ArrayList<int>; you must write ArrayList<Integer>. This is where Wrapper Classes come in.

Every one of Java's 8 primitive types has a corresponding Wrapper Class that boxes the primitive inside an Object: - byte → Byte - short → Short - int → Integer - long → Long - float → Float - double → Double - char → Character - boolean → Boolean

Beyond enabling collections, Wrapper Classes provide extremely useful utility methods. Integer.parseInt("42") converts a String to an int. Integer.MAX_VALUE gives the largest possible int value (2,147,483,647). Integer.toBinaryString(255) converts a number to its binary representation.

Syntax

Using the 8 Wrapper Classes
java
public class Main {
    public static void main(String[] args) {
        // 1. Wrapping a primitive into an Object
        Integer myInt = Integer.valueOf(42);
        Double myDouble = Double.valueOf(3.14);
        Boolean myBool = Boolean.valueOf(true);
        
        // 2. Parsing Strings to primitives (Most common use!)
        int parsed = Integer.parseInt("100");
        double pi = Double.parseDouble("3.14159");
        boolean flag = Boolean.parseBoolean("true"); // case-insensitive
        
        // 3. Useful Constants
        System.out.println(Integer.MAX_VALUE); // 2,147,483,647
        System.out.println(Integer.MIN_VALUE); // -2,147,483,648
        System.out.println(Double.MAX_VALUE);
        
        // 4. Number Base Conversions
        System.out.println(Integer.toBinaryString(255)); // "11111111"
        System.out.println(Integer.toHexString(255));    // "ff"
        System.out.println(Integer.toOctalString(255));  // "377"
        
        // 5. Comparing Wrapper objects correctly
        Integer a = 200;
        Integer b = 200;
        System.out.println(a == b);       // false! (different objects)
        System.out.println(a.equals(b));  // true  (same value)
    }
}

Common Pitfalls

  • Using == to compare Integer objects outside the cache range. Java caches Integer objects for values -128 to 127. For values in this range, Integer a = 100; Integer b = 100; a == b returns true because they point to the same cached object. For values outside this range (like 200), it returns false because new objects are created. Always use .equals() for object comparison.
  • Unboxing a null Wrapper class. If an Integer variable is null and you try to use it in arithmetic (int x = nullableInteger + 1), Java attempts to unbox the null to an int, causing a NullPointerException. Always null-check Wrapper class variables before arithmetic.
  • Ignoring the performance overhead of boxing/unboxing in tight loops. If you have a loop running millions of times and you're doing Integer sum = 0; sum += i;, the constant boxing and unboxing creates millions of temporary objects. Always use primitives inside performance-critical loops.

Interview Questions

Why can't primitives be used directly as generic type parameters (e.g., ArrayList<int>)?

Java Generics are implemented through type erasure, which the compiler uses at the bytecode level to work with the Object class. Primitives are not Objects; they are raw value types stored on the Stack. Therefore, Generics require Object types, and Wrapper classes bridge this gap.

What is the Integer Cache in Java and why does it matter?

To optimize memory, Java pre-creates and caches Integer objects for all values from -128 to 127 at JVM startup. When you autobox an int in this range, you get a cached object, so Integer a = 100; Integer b = 100; a == b evaluates to true. Outside this range, new objects are created, and == returns false. This is why equals() must always be used for Integer comparison.

Real-World Example

JSON parsing libraries (like Gson or Jackson) use Wrapper types instead of primitives for object fields because Wrapper types can represent null — indicating a missing JSON field. A primitive int cannot be null, but Integer age can, accurately reflecting optional JSON data.

example
java
// With Integer (nullable), we can detect missing JSON fields
public class UserProfile {
    String name;
    Integer age;   // Can be null if "age" key missing from JSON
    Boolean active; // Can be null if "active" key missing from JSON
}

// If 'age' is missing from JSON, Jackson sets it to null
// A primitive 'int age' would default to 0 — wrong meaning!

Check Your Knowledge

Test your understanding of Wrapper Classes with these quick questions.

Question 1

Which method converts the String "42" into the primitive `int` value 42?

Question 2

Why does `Integer a = 200; Integer b = 200; a == b` evaluate to `false`?

Question 3

What happens if you try to unbox a `null` Integer into a primitive int?

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

Wrapper Classes

Overview

Java's Collections Framework (ArrayList, HashMap, HashSet) is built entirely using Generics. Generics require types to be Objects, not primitives. You cannot write ArrayList<int>; you must write ArrayList<Integer>. This is where Wrapper Classes come in.

Every one of Java's 8 primitive types has a corresponding Wrapper Class that boxes the primitive inside an Object: - byte → Byte - short → Short - int → Integer - long → Long - float → Float - double → Double - char → Character - boolean → Boolean

Beyond enabling collections, Wrapper Classes provide extremely useful utility methods. Integer.parseInt("42") converts a String to an int. Integer.MAX_VALUE gives the largest possible int value (2,147,483,647). Integer.toBinaryString(255) converts a number to its binary representation.

Syntax

Using the 8 Wrapper Classes
java
public class Main {
    public static void main(String[] args) {
        // 1. Wrapping a primitive into an Object
        Integer myInt = Integer.valueOf(42);
        Double myDouble = Double.valueOf(3.14);
        Boolean myBool = Boolean.valueOf(true);
        
        // 2. Parsing Strings to primitives (Most common use!)
        int parsed = Integer.parseInt("100");
        double pi = Double.parseDouble("3.14159");
        boolean flag = Boolean.parseBoolean("true"); // case-insensitive
        
        // 3. Useful Constants
        System.out.println(Integer.MAX_VALUE); // 2,147,483,647
        System.out.println(Integer.MIN_VALUE); // -2,147,483,648
        System.out.println(Double.MAX_VALUE);
        
        // 4. Number Base Conversions
        System.out.println(Integer.toBinaryString(255)); // "11111111"
        System.out.println(Integer.toHexString(255));    // "ff"
        System.out.println(Integer.toOctalString(255));  // "377"
        
        // 5. Comparing Wrapper objects correctly
        Integer a = 200;
        Integer b = 200;
        System.out.println(a == b);       // false! (different objects)
        System.out.println(a.equals(b));  // true  (same value)
    }
}

Common Pitfalls

  • Using == to compare Integer objects outside the cache range. Java caches Integer objects for values -128 to 127. For values in this range, Integer a = 100; Integer b = 100; a == b returns true because they point to the same cached object. For values outside this range (like 200), it returns false because new objects are created. Always use .equals() for object comparison.
  • Unboxing a null Wrapper class. If an Integer variable is null and you try to use it in arithmetic (int x = nullableInteger + 1), Java attempts to unbox the null to an int, causing a NullPointerException. Always null-check Wrapper class variables before arithmetic.
  • Ignoring the performance overhead of boxing/unboxing in tight loops. If you have a loop running millions of times and you're doing Integer sum = 0; sum += i;, the constant boxing and unboxing creates millions of temporary objects. Always use primitives inside performance-critical loops.

Interview Questions

Why can't primitives be used directly as generic type parameters (e.g., ArrayList<int>)?

Java Generics are implemented through type erasure, which the compiler uses at the bytecode level to work with the Object class. Primitives are not Objects; they are raw value types stored on the Stack. Therefore, Generics require Object types, and Wrapper classes bridge this gap.

What is the Integer Cache in Java and why does it matter?

To optimize memory, Java pre-creates and caches Integer objects for all values from -128 to 127 at JVM startup. When you autobox an int in this range, you get a cached object, so Integer a = 100; Integer b = 100; a == b evaluates to true. Outside this range, new objects are created, and == returns false. This is why equals() must always be used for Integer comparison.

Real-World Example

JSON parsing libraries (like Gson or Jackson) use Wrapper types instead of primitives for object fields because Wrapper types can represent null — indicating a missing JSON field. A primitive int cannot be null, but Integer age can, accurately reflecting optional JSON data.

example
java
// With Integer (nullable), we can detect missing JSON fields
public class UserProfile {
    String name;
    Integer age;   // Can be null if "age" key missing from JSON
    Boolean active; // Can be null if "active" key missing from JSON
}

// If 'age' is missing from JSON, Jackson sets it to null
// A primitive 'int age' would default to 0 — wrong meaning!

Check Your Knowledge

Test your understanding of Wrapper Classes with these quick questions.

Question 1

Which method converts the String "42" into the primitive `int` value 42?

Question 2

Why does `Integer a = 200; Integer b = 200; a == b` evaluate to `false`?

Question 3

What happens if you try to unbox a `null` Integer into a primitive int?

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