What javac does
Autoboxing
Integer.valueOf on the way in, intValue() on the way out, and a checkcast in between.
Autoboxing is method calls that javac writes for you: Integer.valueOf(int) to box, intValue() to unbox. Collections hold Objects, so after next() or get() comes a checkcast to Integer before the unboxing call.
The source
// Autoboxing: Integer.valueOf on the way in, intValue() on the way out.
import java.util.ArrayList;
import java.util.List;
public class Boxing {
static int sum(List<Integer> values) {
int total = 0;
for (Integer v : values) {
total += v;
}
return total;
}
static List<Integer> squares(int n) {
List<Integer> out = new ArrayList<>();
for (int i = 0; i < n; i++) {
out.add(i * i);
}
return out;
}
static boolean same(Integer a, Integer b) {
return a == b;
}
}Compiled by javac 25 with -g and --release 8 to 25. Where releases produce different bytecode, each version is shown.
What to look for
- In
squares,out.add(i * i)isimul,invokestaticInteger.valueOf,invokeinterfaceList.add, thenpop:addreturns a boolean nobody uses. same(a, b)compiles toif_acmpne: it compares references, not values.valueOfreturns cached objects for -128 to 127, so it is true for small numbers and false for large ones.- Unboxing null throws NullPointerException from
intValue(); there is no null check in the bytecode.