| 4 | // Visit http://OnJava8.com for more book information. |
| 5 | |
| 6 | public class Equivalence { |
| 7 | static void show(String desc, Integer n1, Integer n2) { |
| 8 | System.out.println(desc + ":"); |
| 9 | System.out.printf( |
| 10 | "%d==%d %b %b%n", n1, n2, n1 == n2, n1.equals(n2)); |
| 11 | } |
| 12 | @SuppressWarnings("deprecation") |
| 13 | public static void test(int value) { |
| 14 | Integer i1 = value; // [1] |
| 15 | Integer i2 = value; |
| 16 | show("Automatic", i1, i2); |
| 17 | // Old way, deprecated in Java 9 and on: |
| 18 | Integer r1 = new Integer(value); // [2] |
| 19 | Integer r2 = new Integer(value); |
| 20 | show("new Integer()", r1, r2); |
| 21 | // Preferred in Java 9 and on: |
| 22 | Integer v1 = Integer.valueOf(value); // [3] |
| 23 | Integer v2 = Integer.valueOf(value); |
| 24 | show("Integer.valueOf()", v1, v2); |
| 25 | // Primitives can't use equals(): |
| 26 | int x = value; // [4] |
| 27 | int y = value; |
| 28 | // x.equals(y); // Doesn't compile |
| 29 | System.out.println("Primitive int:"); |
| 30 | System.out.printf("%d==%d %b%n", x, y, x == y); |
| 31 | } |
| 32 | public static void main(String[] args) { |
| 33 | test(127); |
| 34 | test(128); |
| 35 | } |
| 36 | } |
| 37 | /* Output: |
| 38 | Automatic: |
| 39 | 127==127 true true |
nothing calls this directly
no outgoing calls
no test coverage detected