bhylu.com

Advertisements

Java Boxing, Unboxing and Missing Numbers

Wrapper classes let primitive-like values participate in generic collections. They also introduce object identity and nullability, which primitive arithmetic does not have.

Understand the idea

Integer, Long, Double and the other wrappers are reference types. Autoboxing converts suitable primitive values into wrappers, and unboxing obtains a primitive value from a wrapper. Generic type parameters use reference types, so List<Integer> is valid while List<int> is not. A nullable Integer is a missing object reference, not a numeric zero. Decide how absence should behave before unboxing at a boundary.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

public class Main {
    public static void main(String[] args) {
        Integer entered = Integer.valueOf("18");
        int total = entered + 4;
        Integer missing = null;
        System.out.println(total);
        System.out.println(missing == null);
    }
}

Expected output

22
true

The addition unboxes entered into an int and produces twenty-two. The second check inspects a missing reference without attempting arithmetic on it. Numeric parsing has its own failure contract: malformed text or an out-of-range integer throws NumberFormatException rather than returning an arbitrary default.

Check the official Java documentation for detailed contracts and supported options.