Back to questions
JuniorTheoryCommon
What does the program print (lines separated by spaces)?
public class Main {
public static void main(String[] args) {
Integer a = 20;
Integer b = 20;
Integer c = 200;
Integer d = 200;
System.out.println(a == b);
System.out.println(c == d);
System.out.println(c.equals(d));
}
}true false true
- Expecting
trueforc == d:==on twoIntegerobjects compares references, and boxing200creates a new object each time. - Expecting
falsefora == b:Integer.valueOfreturns one cached object for every number from-128to127, so both20s share it.
- What does
c == 200give whencis anIntegerholding200? - Why is
equalsthe safe way to compare twoIntegervalues?