Wrappers and null

Integer can be null, int cannot.

Every primitive has a wrapper class: int and Integer, long and Long, boolean and Boolean. A wrapper is an object. You can put it into an old-style collection, and you can assign null to it. A primitive is never null: an uninitialized int field equals 0, and 0 is indistinguishable from "there was no value yet".

Autoboxing turns an int into an Integer by itself. Unboxing goes the other way. The dangerous spot is unboxing null: Integer n = null; int x = n; throws a NullPointerException. That is not "zero", that is a crash. In a service, this is how fields die when they arrive from JSON as missing.

Integer.parseInt("12") returns the primitive 12. On the text "12a" the method throws a NumberFormatException. That is a spot you must handle: external input is parsed inside a try, or its shape is checked first. Do not catch Exception "just in case" around the whole program.

Compare wrappers with equals, or unbox them into a primitive on purpose first. Integer.valueOf(200) == Integer.valueOf(200) can be false: small numbers are cached, large ones are not. This is what trips up tests that "passed yesterday".

Practice

  1. What can be null

    Which of these can hold null?

    • int
    • Integer
    • boolean
    • char
  2. A successful parse

    What number does Integer.parseInt("08") return? Write the number without quotes.

  3. Parse or bad

    Write static String parse(String s). If s is an integer, return its decimal form without leading zeros. Otherwise return bad.