Sub topic 2
Meet the wrapper classes
This chapter assumes you know Java's primitive types (int, long, double, boolean, char), basic class and object syntax, how == and equals differ on objects, and basic List and Map use with generics. It introduces the eight wrapper classes and what they offer. The next chapters cover the conversions the compiler inserts between primitives and wrappers, and the problems those conversions cause.
What a wrapper class is
A wrapper class is a class whose only job is to hold one primitive value inside an object. Each of the eight primitive types has one wrapper in java.lang, so you can use them without an import.
| Primitive | Wrapper | Size of the primitive | Default as a field |
|---|---|---|---|
| `byte` | `Byte` | 8 bits | `0` |
| `short` | `Short` | 16 bits | `0` |
| `int` | `Integer` | 32 bits | `0` |
| `long` | `Long` | 64 bits | `0L` |
| `float` | `Float` | 32 bits | `0.0f` |
| `double` | `Double` | 64 bits | `0.0` |
| `char` | `Character` | 16 bits | `'\u0000'` |
| `boolean` | `Boolean` | not fixed by the language | `false` |
Two names differ from their primitives: Integer and Character. The other six simply capitalize the primitive name. This is a common source of typos such as Int or Char, which do not exist.
The default column applies to primitive fields. A field of the wrapper type defaults to null, like any other reference.
Why Java needs them
Java keeps primitives for speed. A primitive int is the value itself, stored directly in a local variable, a field, or an array slot. A reference to an object adds a pointer, an object header, and work for the garbage collector. Wrappers exist because several parts of the language only work with objects.
- Generics. Type arguments must be reference types.
List<int>does not compile, butList<Integer>does. - Absence of a value. A primitive always holds something. A wrapper can be
null, which can mean "not set" or "unknown". - Methods and constants. Primitives have no methods. The wrapper classes hold parsing, comparison, and conversion helpers, plus constants like
Integer.MAX_VALUE. - APIs that take
Object. Methods such asMap.putorString.formataccept objects, so a primitive has to be wrapped before it can be passed.
The null distinction shows up directly in class design:
public class Product {
int quantity; // primitive field: defaults to 0
Integer discount; // wrapper field: defaults to null
public static void main(String[] args) {
Product p = new Product();
System.out.println(p.quantity); // 0
System.out.println(p.discount); // null
}
}With the primitive you cannot tell "quantity is zero" apart from "quantity was never set". With the wrapper you can, because null means "never set". That extra state costs you in other ways, which later chapters cover.
The class hierarchy
Six of the wrappers share a parent. Boolean and Character do not, because they are not numbers.
Number is an abstract class. Other classes extend it too, such as BigInteger, BigDecimal, and AtomicInteger, so Number is broader than "the six numeric wrappers". You cannot write new Number(), but you can use Number as a type when a method should accept any numeric object.
Each wrapper also implements Comparable for its own type (Integer implements Comparable<Integer>), and all of them are Serializable.
The Number conversion methods
Number declares methods that convert the wrapped value to each numeric primitive: byteValue(), shortValue(), intValue(), longValue(), floatValue(), and doubleValue(). Every numeric wrapper implements all six.
public class NumberMethods {
public static void main(String[] args) {
Number n = Integer.valueOf(300);
System.out.println(n.intValue()); // 300
System.out.println(n.doubleValue()); // 300.0
System.out.println(n.byteValue()); // 44
Double d = 3.99;
System.out.println(d.intValue()); // 3
Long big = 3_000_000_000L;
System.out.println(big.intValue()); // -1294967296
}
}These methods behave like casts, not like checked conversions.
byteValue()on 300 keeps only the low 8 bits. 300 minus 256 is 44, so you get 44.intValue()on aDoubledrops the fractional part toward zero. 3.99 becomes 3, not 4.intValue()on aLongthat does not fit in 32 bits wraps around and produces a negative number.
None of these calls throws an exception. If you need to know whether a narrowing conversion is safe, check the range yourself, or use Math.toIntExact(long), which throws ArithmeticException on overflow.
Constants
The numeric wrappers define the limits of their type. These are public static final fields, so you read them from the class name.
public class WrapperConstants {
public static void main(String[] args) {
System.out.println(Byte.MIN_VALUE + " to " + Byte.MAX_VALUE); // -128 to 127
System.out.println(Short.MIN_VALUE + " to " + Short.MAX_VALUE); // -32768 to 32767
System.out.println(Integer.MIN_VALUE + " to " + Integer.MAX_VALUE); // -2147483648 to 2147483647
System.out.println(Long.MAX_VALUE); // 9223372036854775807
System.out.println(Integer.SIZE + " bits, " + Integer.BYTES + " bytes"); // 32 bits, 4 bytes
System.out.println(Double.MAX_VALUE); // 1.7976931348623157E308
System.out.println(Double.MIN_VALUE); // 4.9E-324
System.out.println((int) Character.MAX_VALUE); // 65535
System.out.println(Boolean.TRUE); // true
}
}SIZE is the width in bits and BYTES is the width in bytes.
Helpers on each wrapper
Beyond constants, each wrapper carries static methods for its own type. You will meet the parsing methods in a later chapter. Here is a sample of the others, so you know where to look before writing your own versions.
public class WrapperHelpers {
public static void main(String[] args) {
// Integer and Long
System.out.println(Integer.toBinaryString(10)); // 1010
System.out.println(Integer.toHexString(255)); // ff
System.out.println(Integer.bitCount(255)); // 8
System.out.println(Integer.max(3, 9)); // 9
System.out.println(Integer.sum(4, 5)); // 9
System.out.println(Integer.signum(-12)); // -1
// Character
System.out.println(Character.isDigit('7')); // true
System.out.println(Character.isLetter('7')); // false
System.out.println(Character.toUpperCase('a')); // A
System.out.println(Character.getNumericValue('7')); // 7
// Boolean
System.out.println(Boolean.logicalXor(true, false)); // true
System.out.println(Boolean.parseBoolean("TRUE")); // true
}
}Integer.max and Integer.sum look redundant, but they exist so you can pass them as method references, for example reduce(0, Integer::sum). Character.getNumericValue('7') returns the number 7. Casting (int) '7' returns 55, the character's code.
A related detail: Boolean.parseBoolean returns true only when the text equals "true", ignoring case. Any other string, including "yes", "1", or null, gives false with no error.
Immutability
Every wrapper object is immutable. Once created, the value inside cannot change, and the classes have no setters. They are also final, so you cannot subclass them.
This matters when you expect a method to modify its argument:
public class ImmutableDemo {
static void increment(Integer value) {
value++; // creates a new Integer, assigns it to the local variable
System.out.println("inside: " + value);
}
public static void main(String[] args) {
Integer count = 5;
increment(count);
System.out.println("outside: " + count);
}
}This prints inside: 6 and then outside: 5. Java passes the reference by value. Inside the method, value++ builds a different Integer object and points the local variable at it. The caller's variable still points at the original 5. The compiler-generated steps behind value++ are the subject of the next chapter.
Immutability has useful consequences. Wrapper objects are safe to share between threads, safe to use as HashMap keys, and safe for the runtime to cache and reuse. The caching is why == can give surprising answers on wrappers, which gets its own chapter.
Equality in one paragraph
Because wrappers are objects, == between two wrapper variables compares references, not values. new-style identity and value equality are different questions, and the wrapper classes override equals so that it compares the wrapped values. Whether two Integer variables holding the same number are the same object depends on how they were created. For now, remember that equals is the safe default, and the later chapters on the cache and on comparison explain why.
Choosing between a primitive and a wrapper
Use a primitive by default. Use a wrapper when the language or API requires an object, or when you need null to carry meaning.
- Local variables, loop counters, and arithmetic: use primitives.
- Type arguments for
List,Map,Set,Optional, and other generics: use wrappers. - Fields where "no value" is a real state, such as an optional discount read from a database column that allows nulls: a wrapper can model it. Think about
Optionalor a sentinel value as alternatives. - Method parameters and return types: prefer primitives unless
nullis a meaningful answer. A method returningIntegerforces every caller to considernull.
Other classes you will see
Void is a placeholder class with no instances. It appears as a type argument when a generic type needs a return type but nothing is returned, for example Callable<Void>. It is not a wrapper for anything, since void is not a value.
BigInteger and BigDecimal are also Number subclasses, but they are not wrappers. They do not wrap a primitive. They hold arbitrary-size values and are used when long or double do not have enough range or precision.
Common mistakes at this stage
- Assuming
Double.MIN_VALUEis negative. It is the smallest positive double. - Treating
intValue()as a safe conversion. It silently truncates or wraps. - Trying to modify a wrapper through a method argument. The change does not reach the caller.
- Declaring
Integerfields or return types out of habit. This addsnullas a possible value you then have to handle. - Expecting
Boolean.parseBoolean("yes")to returntrue.
Exercise
A method has the signature static void reset(Integer value) and its body is value = 0;. After calling reset(count) with Integer count = 9;, what does count hold, and why?
Show answer
It still holds 9. Java passes the reference by value, so the assignment only changes the method's local variable to point at a different Integer. The caller's variable still points at the original object. Wrapper objects are also immutable, so there is no way to change the 9 in place.
Exercise
What do Long big = 5_000_000_000L; System.out.println(big.intValue()); and Double d = -2.7; System.out.println(d.intValue()); print?
Show answer
The first prints 705032704, because 5,000,000,000 minus 4,294,967,296 leaves 705,032,704, the value left after the low 32 bits are kept. The second prints -2, because intValue() truncates toward zero rather than rounding down. Neither call throws an exception.
Exercise
Why does List<int> ids = new ArrayList<>(); fail to compile, and what is the fix?
Show answer
Generic type arguments must be reference types, and int is a primitive. Use the wrapper: List<Integer> ids = new ArrayList<>();.