Reading history

Java Wrapper Classes and Autoboxing

5 min read 0 views

Learn Java wrapper classes like Integer and Double: autoboxing and unboxing, parseInt and other helpers, the Integer cache == trap, null unboxing and performance.

Java has eight primitive types, such as int, double and boolean, which are fast but are not objects. Each one has a matching wrapper class: Integer, Double, Boolean and so on. Wrappers let numbers live in collections like ArrayList, carry useful methods such as Integer.parseInt, and can be null. Java converts between the two automatically, which is called autoboxing and unboxing. This lesson shows how that works and the traps it hides.

In this lesson you will learn

  • The eight wrapper classes and why they exist
  • Autoboxing and unboxing
  • Parsing strings and other helper methods
  • Why == on wrappers gives surprising results
  • Null unboxing and performance traps

This lesson builds on Java variables and data types and ArrayList.

Boxing, Unboxing and Helper Methods

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // Primitives cannot go into collections, wrappers can
        List<Integer> marks = new ArrayList<>();
        marks.add(88);                       // autoboxing: int -> Integer
        marks.add(92);
        int first = marks.get(0);            // unboxing: Integer -> int
        System.out.println(marks + " first=" + first);

        // Parsing text and converting back
        int age = Integer.parseInt("21");
        double cgpa = Double.parseDouble("3.75");
        String bin = Integer.toBinaryString(10);
        System.out.println(age + 1 + " " + cgpa + " " + bin + " " + Integer.parseInt("1010", 2));

        // Useful constants and helpers
        System.out.println(Integer.MAX_VALUE + " " + Integer.MIN_VALUE);
        System.out.println(Character.isDigit('7') + " " + Character.toUpperCase('b')
                + " " + Boolean.parseBoolean("TRUE"));
        System.out.println(Integer.compare(5, 9) + " " + Integer.sum(5, 9) + " " + Double.isNaN(0.0 / 0.0));
    }
}

Output

[88, 92] first=88
22 3.75 1010 10
2147483647 -2147483648
true B true
-1 14 true
  • Collections hold objects, so List<int> is not allowed. marks.add(88) works because Java autoboxes the int into an Integer, and int first = marks.get(0) unboxes it back.
  • Integer.parseInt and Double.parseDouble turn text into numbers, which you need for user input and files. parseInt("1010", 2) reads a binary number.
  • age + 1 + " " printed 22 because Java adds the two numbers before it reaches the string.
  • Integer.MAX_VALUE and MIN_VALUE give the limits of an int.
  • Character has tests such as isDigit and isLetter; Boolean.parseBoolean ignores case.
  • Integer.compare(5, 9) returns a negative number, which is what sorting code expects. 0.0 / 0.0 is “not a number”, detected with Double.isNaN.

Four Wrapper Traps

public class Main {
    public static void main(String[] args) {
        Integer a = 127, b = 127;
        Integer c = 128, d = 128;
        System.out.println("a == b: " + (a == b));            // cached small values
        System.out.println("c == d: " + (c == d));            // different objects
        System.out.println("c.equals(d): " + c.equals(d));    // compares values

        Integer bonus = null;                                 // wrappers can be null
        try {
            int total = 1000 + bonus;                         // unboxing null
            System.out.println(total);
        } catch (NullPointerException e) {
            System.out.println("NullPointerException when unboxing null");
        }

        try {
            Integer.parseInt("12a");
        } catch (NumberFormatException e) {
            System.out.println("NumberFormatException: " + e.getMessage());
        }

        Long sumBoxed = 0L;
        for (int i = 0; i < 1_000_000; i++) sumBoxed += i;    // creates many objects
        long sumPrim = 0;
        for (int i = 0; i < 1_000_000; i++) sumPrim += i;
        System.out.println(sumBoxed.equals(sumPrim) + " (same result either way)");
    }
}

Output

a == b: true
c == d: false
c.equals(d): true
NullPointerException when unboxing null
NumberFormatException: For input string: "12a"
true (same result either way)
  • Comparing with ==: for objects, == checks whether two references point to the same object. Java caches Integer objects from -128 to 127, so 127 == 127 happens to be true, but 128 == 128 is false. Always compare wrapper values with equals(), or unbox to int first.
  • Unboxing null: a wrapper can be null, meaning “no value”. Using it in arithmetic forces unboxing and throws a NullPointerException.
  • Parsing bad text throws NumberFormatException, so wrap user input in try/catch.
  • Hidden objects in loops: Long sumBoxed creates a new Long object on every addition. The result is the same, but a primitive long is much faster and uses less memory.

Primitive Types and Their Wrappers

PrimitiveWrapperParse method
byteByteByte.parseByte
shortShortShort.parseShort
intIntegerInteger.parseInt
longLongLong.parseLong
floatFloatFloat.parseFloat
doubleDoubleDouble.parseDouble
charCharacter(use s.charAt(0))
booleanBooleanBoolean.parseBoolean

parseInt returns a primitive int; Integer.valueOf returns an Integer object and uses the cache. Wrapper objects are immutable: count++ on an Integer creates a new object.

Common Mistakes

  1. Using == to compare Integer or Long values, which works in testing with small numbers and fails later with large ones.
  2. Returning null from a method declared to return Integer, then assigning it to an int.
  3. Using wrapper types for counters and loop variables when a primitive would do.
  4. Calling map.get(key) into an int; it returns null for missing keys. Use getOrDefault.

Practice Exercises

Exercise 1. Convert the strings "15", "x7" and "42" to numbers and print their sum, skipping invalid ones.

Show answer
int sum = 0;
for (String s : new String[] {"15", "x7", "42"}) {
    try {
        sum += Integer.parseInt(s);
    } catch (NumberFormatException e) {
        System.out.println("skipped " + s);
    }
}
System.out.println(sum);   // 57

Exercise 2. What does this print? Integer x = 1000, y = 1000; System.out.println(x.equals(y) + " " + (x.intValue() == y));

Show answer

true true. equals compares values, and when one side of == is a primitive, Java unboxes the other side and compares numbers.

Frequently Asked Questions

Should I use int or Integer?

Use int by default: it is faster and can never be null. Use Integer when you need an object, such as in collections and generics, or when “no value” (null) has a real meaning.

Can I change the Integer cache range?

The upper limit can be raised with a JVM option, but code should never depend on it. Compare values with equals() and the cache does not matter.

Summary

  • Each primitive has a wrapper class so it can be used as an object.
  • Autoboxing and unboxing convert between them automatically.
  • Compare wrappers with equals(), never ==.
  • Unboxing null throws an exception; prefer primitives in calculations.

Next: Java Comparable and Comparator.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *