Integer, Double and friends wrap primitives in objects so they can go into collections. Java converts back and forth automatically, with one trap.
Java · beginner · 8 min · 12 steps · free
import java.util.ArrayList;
public class WrapperDemo {
public static void main(String[] args) {
int raw = 42;
Integer boxed = raw; // autoboxing: int to Integer
int back = boxed; // unboxing: Integer to int
int parsed = Integer.parseInt("17");
ArrayList<Integer> list = new ArrayList<>();
list.add(7); // 7 is boxed to fit in the list
Integer big1 = 1000;
Integer big2 = 1000;
boolean sameObject = big1 == big2;
boolean sameValue = big1.equals(big2);
System.out.println(back + parsed + " " + sameObject + " " + sameValue);
}
}main. args holds its command-line arguments (none here). raw is created on the stack with the value 42.Integer.parseInt turns text into an int.list is created on the stack and points to a new ArrayList on the heap: [].big1 is created on the stack and points to a new Integer on the heap: 1000.big2 is created on the stack and points to a new Integer on the heap: 1000.== on two Integer objects compares references. Two separate 1000 objects: false.sameValue is created on the stack with the value true.59 false true.Answer: Character. char → Character.
Answer: Usually false. == compares references.
← StringBuilder: Changeable Text · Java Strings: Creation and Immutability →