0% completed
Primitive Types and Wrapper Classes
On This Page
What are the primitive types, and why do wrapper classes exist?
Why does == sometimes work and sometimes fail for Integer objects?
What does autoboxing cost, and when does it throw?
What happens on integer overflow and on a narrowing cast?
Predict the Output
Key Takeaways
Integer oldApple = 120; Integer newApple = 120; Integer oldCherry = 300; Integer newCherry = 300; System.out.println(oldApple == newApple); // true System.out.println(oldCherry == newCherry); // false
Both comparisons look the same, and in both cases the two prices are equal. The first one prints true and the second one prints false, because == on two Integer variables does not compare the prices.
The four questions are about numbers in Java: which types exist, what == compares, what it costs to convert between int and Integer, and what happens when a value does not fit in its type.
What are the primitive types, and why do wrapper classes exist?
Level: Junior
Java has eight primitive types that hold a plain value, and each one has a wrapper class that holds the same value inside an object. Wrapper classes exist because some parts of the language work only with objects. A List<int> does not compile, and an int can never be null.
| Primitive | Size in bits | Values | Wrapper class |
|---|---|---|---|
byte | 8 | -128 to 127 | Byte |
short | 16 | -32,768 to 32,767 | Short |
int | 32 | about -2.1 billion to 2.1 billion | Integer |
long | 64 | about -9.2 to 9.2 times 10 to the power 18 | Long |
char | 16 | 0 to 65,535 | Character |
float | 32 | about 7 decimal digits of precision | Float |
double | 64 | about 15 decimal digits of precision | Double |
boolean | Not specified | true and false | Boolean |
A variable of a primitive type contains the value itself. A variable of a wrapper type contains a reference, which is a value that identifies an object in memory, and the primitive value is stored inside that object.
Wrapper classes serve three purposes. They allow numbers in collections and other generic types, they can represent a missing value with null, and they provide methods and constants such as Integer.parseInt() and Integer.MAX_VALUE. A stock map therefore has the type Map<String, Integer>, and its get() method can return null for an unknown product.
Common mistake: Saying that String is a primitive type because it has literals. String is a class, and a String variable holds a reference.
Follow-up questions
1. Does a variable of a primitive type always have a default value?
<details><summary>Show answer</summary>No, fields and array elements have default values, but local variables do not. A numeric field starts at zero, a boolean field starts as false, and a field of any reference type starts as null. The compiler rejects code that reads a local variable before a value is assigned to it.
2. Why does byte c = a + b fail to compile when a and b are byte variables that are not final?
The sum of two byte values has the type int. Java converts the operands of + to at least int before it adds them, which is called numeric promotion. The compiler then reports incompatible types: possible lossy conversion from int to byte. An explicit cast, (byte) (a + b), makes the code compile and accepts the possible loss.
Why does == sometimes work and sometimes fail for Integer objects?
Level: Junior
When both operands are Integer objects, == compares references, and the conversion from int reuses one object for each value from -128 to 127. Two variables that receive 120 in this way therefore refer to the same object. Two variables that receive 300 normally refer to two different objects, so == returns false.
The assignment Integer oldApple = 120 converts an int to an Integer. The compiler turns this conversion into a call to Integer.valueOf(120). That method reads from an array of Integer objects, called the Integer cache, which holds one object for every value in the range. The method returns an object from this array when the value is in the range, and it creates a new object when the value is outside.
The program below boxes each value twice and compares the two references.
-129: same object = false -128: same object = true 0: same object = true 120: same object = true 127: same object = true 128: same object = false 300: same object = false equals: true == with an int: true
The result changes exactly at the two limits of the cache. The last two lines use the price 300, which is outside the cache. equals() compares the numbers, so it returns true. The last line also prints true, because one operand is an int, and Java then converts the other operand to int and compares two numbers.
Look at the arrows on each side. Both variables on the left refer to one object, and the variables on the right refer to two objects with the same value. The safe comparison for two wrapper objects is equals().
Common mistake: Testing code that compares Integer objects with == only with small numbers. Such a test passes for every value up to 127, and the same code fails for the first price of 128 or more.
Follow-up questions
1. Which other wrapper classes have a cache?
<details><summary>Show answer</summary>Byte, Short, and Long cache -128 to 127, Character caches 0 to 127, and Boolean has two shared objects. The Byte cache covers every byte value. The valueOf() methods of Float and Double create a new object each time, so two boxed double values of 1.0 are different objects.
2. Can the range of the Integer cache change?
<details><summary>Show answer</summary>The upper limit can be raised with the JVM option -XX:AutoBoxCacheMax, and the lower limit is fixed at -128. With the value 1000, the comparison of the two cherry prices returns true. The language guarantees sharing for constants from -128 to 127, and valueOf() documents it for every int in that range. Neither makes a promise for other values, so a program must not depend on either result.
What does autoboxing cost, and when does it throw?
Level: Mid-level
Boxing a value outside the cache creates an object, and unboxing a null reference throws NullPointerException. The automatic conversion from a primitive to its wrapper is called autoboxing, and the conversion in the other direction is called unboxing. Neither one is visible in the source code, so both the cost and the exception are easy to miss.
The compiler inserts the method calls. The statement count = count + 1, where count is an Integer, compiles to the same instructions as this line:
count = Integer.valueOf(count.intValue() + 1);
The statement therefore unboxes the old value, adds 1, and boxes the result. A loop that runs this statement 1,000,000 times performs 1,000,000 unboxing conversions and 1,000,000 boxing conversions.
Boxed numbers also take more memory. On a typical 64-bit JVM with compressed references, an Integer object takes 16 bytes, which is a 12-byte header and a 4-byte int. Each reference to it takes another 4 bytes. A list of 1,000 prices above 127 needs about 20,000 bytes for references and objects, while the elements of an int[] with the same prices take 4,000 bytes.
The program below boxes the numbers 1 to 500 twice and counts the different objects. It then unboxes two values from a map.
Boxing conversions: 1000 Different objects: 873 apples: 50 kiwis: NullPointerException
The numbers 1 to 127 came from the cache both times, which accounts for 127 objects. The other 373 numbers created an object on each pass, and 2 x 373 is 746. The total is 873. In the last line, the map had no entry for kiwi, so get() returned null, and the assignment to an int called intValue() on null.
Common mistake: Declaring a loop total as Long or Integer out of habit. The wrapper type adds an unboxing and a boxing conversion to every iteration.
Follow-up questions
1. Does getOrDefault() always prevent the exception when a map value is unboxed?
It prevents the exception for a missing key, but not for a key that is mapped to null. A HashMap returns the stored value when the key is present, and that value can be null. Not storing null in the map removes the problem.
2. Why should a program not use an Integer object as a lock?
The cache can make two unrelated parts of a program share the same object. If both parts lock an Integer that holds 120, one can wait for the other without any reason. The Javadoc of Integer says that instances should not be used for synchronization, and the compiler warns about an attempt to synchronize on an instance of a value-based class.
What happens on integer overflow and on a narrowing cast?
Level: Mid-level
Integer arithmetic keeps only the lowest 32 bits of an int result and the lowest 64 bits of a long result, with no error. An overflow is the case in which a result does not fit its type. A cast to a smaller integer type works the same way, because it keeps the lowest bits and discards the rest.
Java stores whole numbers in two's complement, a format in which the highest bit represents a negative amount. In a byte, that bit represents -128. The number 130 is 10000010 in binary, so a byte with these bits has the value -128 + 2, which is -126.
Look at the highest bit of the result. It represents 128 in the int and -128 in the byte, and the bits themselves did not change.
A cast from double to int follows a different rule. It removes the fraction, and a value that is too large becomes the largest int.
int: -1894967296 too late: -1894967296 long: 2400000000 multiplyExact: integer overflow (byte) 130 = -126 (int) 2.9 = 2 (int) 3e9 = 2147483647 (byte) 3e9 = -1
The correct total, 2,400,000,000 cents, is larger than 2,147,483,647, the largest int. The first line is the correct total minus 2 to the power 32, which is 4,294,967,296. The cast of price to long in the third line makes Java multiply in 64 bits. The last cast has two steps: 3e9 becomes the largest int, and its lowest 8 bits are all 1, which is -1 as a byte.
Common mistake: Assigning the product to a long variable and expecting a correct result. The type of the variable has no effect on the multiplication, which is done in int when both operands are int.
Follow-up questions
1. What does Math.abs(Integer.MIN_VALUE) return?
It returns Integer.MIN_VALUE, which is negative. The range of int has one more negative value than positive values, so 2,147,483,648 does not fit. The method Math.absExact() throws ArithmeticException for this argument instead, as Math.addExact() and Math.multiplyExact() do on overflow.
2. Why does 0.1 + 0.2 print 0.30000000000000004?
A double stores a binary fraction, and 0.1 and 0.2 have no exact binary form. Each literal becomes the nearest double, and the small differences appear in the sum. No overflow is involved. Prices in whole cents avoid the problem, because an int or long stores every whole number in its range exactly.
Predict the Output
Two maps hold the prices that a website and an app display. Write down the seven results before you run the program.
The program prints true, false, true, true, true, true, and false. The price 120 is in the cache, so both maps hold the same object. The price 250 is outside, so == compares two different objects. The operator >= has no meaning for references, so Java unboxes both values and compares 250 with 250. equals() compares two Integer values. The next two lines compare with an int and with a long, and both unbox the Integer and compare numbers. In the last line, expected is boxed to a Long, and Integer.equals() returns false for an object of another class.
Key Takeaways
- A primitive variable holds a value. A wrapper variable holds a reference to an object, which allows generics and
null. ==compares references when both operands are wrapper objects, and it compares numbers when one operand is a primitive number.Integer.valueOf()shares objects for -128 to 127, so compare wrapper objects withequals().- Autoboxing outside the cache creates an object, and unboxing
nullthrowsNullPointerException. - Overflow and integer narrowing keep the lowest bits without an error.
Math.multiplyExact()and similar methods report overflow. - A cast from
doubletointremoves the fraction and stops at the limits ofint.
A primitive variable contains its value and a wrapper variable contains a reference, and this difference also decides what a method receives. The lesson Pass by Value in Java explains what is copied when a method is called.
Reading Progress
0%
On This Page
What are the primitive types, and why do wrapper classes exist?
Why does == sometimes work and sometimes fail for Integer objects?
What does autoboxing cost, and when does it throw?
What happens on integer overflow and on a narrowing cast?
Predict the Output
Key Takeaways