Integer Cache: == versus equals
Problem
In Java, Integer objects for the values -128 to 127 are cached: boxing the same value gives the same object. Other values give a new object each time. For two boxed integers a and b print two words: whether == (same object) is true, and whether equals() (same value) is true. For 127 and 127 the answer is true true. For 128 and 128 it is false true.
Constraints
- -10^6 <= a, b <= 10^6
Examples
Input
127 127
Output
true true
Input
128 128
Output
false true
Solutions
A cache of boxed objects for small values is a memory and speed optimisation. It makes == work by luck for small numbers and fail for big ones. Always compare boxed numbers with equals().
/*
* Problem : Compare boxed integers.
* Input : Two integers a and b.
* Output : Two words: reference equal, value equal.
* Approach: Real or modelled boxing.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String solve(long a, long b) {
// Step 1: Integer.valueOf is what autoboxing calls. It returns a cached object for -128..127.
Integer first = Integer.valueOf((int) a);
Integer second = Integer.valueOf((int) b);
// Step 2: == compares the object references. equals() compares the values.
return (first == second) + " " + first.equals(second);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long a = scanner.nextLong();
long b = scanner.nextLong();
System.out.println(solve(a, b));
}
}
Hints (2)
- Which range is cached?
- Why does == work for 127 and fail for 128?