forked from BruceEckel/OnJava8-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEquivalence.java
More file actions
54 lines (53 loc) · 1.51 KB
/
Equivalence.java
File metadata and controls
54 lines (53 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// operators/Equivalence.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
public class Equivalence {
static void show(String desc, Integer n1, Integer n2) {
System.out.println(desc + ":");
System.out.printf(
"%d==%d %b %b%n", n1, n2, n1 == n2, n1.equals(n2));
}
@SuppressWarnings("deprecation")
public static void test(int value) {
Integer i1 = value; // [1]
Integer i2 = value;
show("Automatic", i1, i2);
// Old way, deprecated in Java 9 and on:
Integer r1 = new Integer(value); // [2]
Integer r2 = new Integer(value);
show("new Integer()", r1, r2);
// Preferred in Java 9 and on:
Integer v1 = Integer.valueOf(value); // [3]
Integer v2 = Integer.valueOf(value);
show("Integer.valueOf()", v1, v2);
// Primitives can't use equals():
int x = value; // [4]
int y = value;
// x.equals(y); // Doesn't compile
System.out.println("Primitive int:");
System.out.printf("%d==%d %b%n", x, y, x == y);
}
public static void main(String[] args) {
test(127);
test(128);
}
}
/* Output:
Automatic:
127==127 true true
new Integer():
127==127 false true
Integer.valueOf():
127==127 true true
Primitive int:
127==127 true
Automatic:
128==128 false true
new Integer():
128==128 false true
Integer.valueOf():
128==128 false true
Primitive int:
128==128 true
*/