Primitives, Wrappers and Autoboxing Questions
45 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)"Why does Integer 127 == 127 give true but 128 == 128 give false?" is a fresher favourite. The interviewer checks that you know primitives, wrappers, autoboxing and the two traps: the Integer cache and unboxing null.
Recap: eight primitives and their wrappers
A primitive is a plain value stored directly in a variable, not an object. Java has eight: byte, short, int, long, float, double, char and boolean. Each has a wrapper class, the object version of the same value.
This program prints the size, range and default value of the main primitive types.
Example 1 · Sizes, ranges and default values
public class PrimitiveFacts { static int count; static long total; static double average; static char grade; static boolean passed; static String name;
public static void main(String[] args) { System.out.println("int: " + Integer.BYTES + " bytes, default " + count); System.out.println("long: " + Long.BYTES + " bytes, default " + total); System.out.println("double: " + Double.BYTES + " bytes, default " + average); System.out.println("char: " + Character.BYTES + " bytes, default code " + (int) grade); System.out.println("boolean default: " + passed); System.out.println("String default: " + name); System.out.println("int range: " + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE); System.out.println("MAX + 1 = " + (Integer.MAX_VALUE + 1)); }}int: 4 bytes, default 0 long: 8 bytes, default 0 double: 8 bytes, default 0.0 char: 2 bytes, default code 0 boolean default: false String default: null int range: -2147483648 to 2147483647 MAX + 1 = -2147483648
What this code does
- Static fields get default values automatically: 0, 0.0, the zero character (code 0),
falseandnullfor a reference such asString. - The last line shows overflow: adding 1 to the largest
intsilently wraps to the smallest, with no exception.
Wrappers are Byte, Short, Integer, Long, Float, Double, Character and Boolean; all are immutable. Sizes: byte 1, short 2, int 4, long 8, float 4, double 8, char 2 bytes. Fields default to 0, 0.0, '\u0000' or false, references to null, and local variables have no default. int overflow wraps silently.
Revise: Java data types (opens in a new tab).
Autoboxing and unboxing
Autoboxing is the Java compiler turning a primitive into its wrapper object automatically, for example list.add(85) becomes list.add(Integer.valueOf(85)). The reverse step, unboxing, calls a method such as intValue().
Autoboxing is not magic at run time: the compiler inserts the calls. This program shows each conversion with the call the compiler adds.
Example 2 · What the compiler inserts for boxing and unboxing
import java.util.ArrayList;import java.util.List;
public class AutoboxingDemo { public static void main(String[] args) { List<Integer> marks = new ArrayList<>(); marks.add(85); // compiler: marks.add(Integer.valueOf(85)) marks.add(92);
int first = marks.get(0); // compiler: marks.get(0).intValue()
Integer total = 0; for (int m : marks) { // each element unboxed to int total += m; }
System.out.println("first = " + first); System.out.println("total = " + total); System.out.println("parseInt: " + (Integer.parseInt("40") + 2)); System.out.println("valueOf: " + Integer.valueOf("40").equals(40)); }}first = 85 total = 177 parseInt: 42 valueOf: true
What this code does
- The comments show the calls the compiler adds.
total += munboxes, adds and boxes a newIntegerevery time round the loop; anint totalwould avoid that. parseIntreturns a primitiveint;valueOfreturns anIntegerobject, which is compared here withequals.
That is why List<Integer> accepts 85 and an Integer can be used in arithmetic. Each boxing may create an object, so heavy number crunching in wrapper types is slower than with primitives.
Revise: Why generics (opens in a new tab) for why collections hold objects.
Predict the output: the Integer cache
The Integer cache is a set of ready-made Integer objects for the values -128 to 127. Autoboxing and Integer.valueOf return the cached object for those values and a new object for any other value.
Two Integers with the same value may or may not be the same object. This program compares 127 with 127 and 128 with 128 using == and equals.
Example 3 · 127 == 127 but 128 != 128
public class IntegerCacheDemo { public static void main(String[] args) { Integer a = 127, b = 127; Integer c = 128, d = 128; int plain = 128; Long big = 127L;
System.out.println("127 == 127: " + (a == b)); System.out.println("128 == 128: " + (c == d)); System.out.println("128 equals 128: " + c.equals(d)); System.out.println("Integer 128 == int 128: " + (c == plain)); System.out.println("Long 127 equals 127: " + big.equals(127)); System.out.println("Long 127 equals 127L: " + big.equals(127L)); }}127 == 127: true 128 == 128: false 128 equals 128: true Integer 128 == int 128: true Long 127 equals 127: false Long 127 equals 127L: true
What this code does
- 127 comes from the cache, so
aandbare the same object. 128 is outside the cache, socanddare two objects and==isfalse;equalscompares values and istrue. c == plainunboxescand compares numbers.big.equals(127)isfalsebecause127boxes to anInteger, and aLongonly equals anotherLong.
So Integer a = 127, b = 127; gives one cached object and a == b is true, while with 128 == compares two different objects and gives false. The rule for interviews and real code is the same: compare wrapper values with equals, never ==.
Predict the output
Predict the wrapper puzzle
Read each snippet and pick what it prints.
Round 1 of 3
Integer x = 128; int y = 128; x == y is true, because x is unboxed to an int.NullPointerException from unboxing null
Unboxing is the Java compiler turning a wrapper object back into a primitive by calling a method such as intValue(). If the wrapper is null, unboxing throws a NullPointerException.
A wrapper can be null, a primitive cannot. This program unboxes a missing map value and shows two fixes.
Example 4 · Unboxing null from a map
import java.util.HashMap;import java.util.Map;
public class UnboxingNpe { public static void main(String[] args) { Map<String, Integer> fees = new HashMap<>(); fees.put("Asha", 45000);
try { int raviFee = fees.get("Ravi"); // get returns null, then null.intValue() System.out.println(raviFee); } catch (NullPointerException e) { System.out.println("NullPointerException: no fee stored for Ravi"); }
int safe = fees.getOrDefault("Ravi", 0); System.out.println("With getOrDefault: " + safe);
Integer maybe = fees.get("Ravi"); System.out.println(maybe == null ? "No record for Ravi" : "Fee: " + maybe); }}NullPointerException: no fee stored for Ravi With getOrDefault: 0 No record for Ravi
What this code does
fees.get("Ravi")returnsnull. Assigning it to anintmakes the compiler callintValue()onnull, which throws.- Two safe versions follow:
getOrDefaultsupplies 0, and keeping the result asIntegerlets you check fornullyourself.
The classic case is int fee = fees.get("Ravi"); when the map has no entry for Ravi: get returns null and the assignment unboxes it. Fixes: getOrDefault(key, 0), an explicit null check, or keeping the value as Integer.
Find the bug
Find the wrapper bug
Each snippet has one wrong line. Tap it, then check the fix.
Read Ravi's fee; he has no record yet.
Round 1 of 3Common questions: why wrappers, int vs Integer, char arithmetic
Numeric promotion is Java widening smaller number types to int (or a larger type) before doing arithmetic. A char, byte or short in an expression becomes an int, so 'A' + 1 is the int 66.
A char is a 16-bit number underneath. This program shows char arithmetic and why char c = c + 1; needs a cast.
Example 5 · char arithmetic
public class CharArithmetic { public static void main(String[] args) { char grade = 'A'; System.out.println(grade + 1); System.out.println((char) (grade + 1)); grade++; System.out.println(grade); System.out.println('A' + 'B'); System.out.println("" + 'A' + 'B'); System.out.println('7' - '0'); }}66 B B 131 AB 7
What this code does
grade + 1isintarithmetic, so it prints 66; the cast gives back the letter.grade++keeps the typecharbecause it includes a hidden cast.'A' + 'B'adds two codes (65 + 66). Starting with""makes it string concatenation, which givesAB.'7' - '0'turns a digit character into the number 7.
Example 6 · remove(int) or remove(Object)?
import java.util.ArrayList;import java.util.List;
public class RemoveTrap { public static void main(String[] args) { List<Integer> rolls = new ArrayList<>(List.of(10, 20, 30, 1));
rolls.remove(1); // remove(int index): removes 20 System.out.println(rolls);
rolls.remove(Integer.valueOf(1)); // remove(Object o): removes the value 1 System.out.println(rolls); }}[10, 30, 1] [10, 30]
What this code does
remove(1)matchesremove(int index)exactly, so no boxing happens and the element at index 1 (20) goes.- Passing an
Integerpicksremove(Object), which removes the value 1. This is a favourite "int vs Integer in collections" question.
Wrappers exist because collections and generics hold only objects, because a wrapper can be null to mean "no value", and for helpers like Integer.parseInt. Use int when the value always exists and Integer when null has a meaning. Turn a digit character into its value with '7' - '0'.
Fix the error
Fix the conversion error
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
Move the grade letter from A to B.
Error
CharFix.java:4: error: incompatible types: possible lossy conversion from int to char
grade = grade + 1;
^List<Integer>, remove(1) removes index 1; remove(Integer.valueOf(1)) removes the value 1.Next step
Check your understanding
12 quick questions