forked from cirosantilli/java-cheat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWrappersCheat.java
More file actions
129 lines (97 loc) · 3.08 KB
/
WrappersCheat.java
File metadata and controls
129 lines (97 loc) · 3.08 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/*
# Primitive wrappers
# Byte
# Char
# Short
# Short
# Float
# Double
Each primitive type has an Object wrapper: Byte, Integer, Char, etc.
Those object wrappers are necessary in situations
where objects are required instead of primitives.
The primitive wrappers have the following magic properties in the language:
- boxing and unboxing conversion
# Number
http://docs.oracle.com/javase/7/docs/api/java/lang/Number.html
Implemented by all primitive wrappers.
Only contains the `xValue` methods.
*/
public class WrappersCheat {
public static void main(String[] args) {
/*
Primitive wrappers are immutable:
http://stackoverflow.com/questions/3815173/increment-a-integers-int-value
This is how you increment them:
*/
{
Integer i = 0;
i = new Integer(i.intValue() + 1);
assert i == 1;
}
/*
# Add wrappers
# Multiply wrappers
The primitive wrappers do not have methods that can be performed directly with operators
such as add and multiply likely because:
- unboxing produces a nice syntax
- the efficiency of unboxing is already optimal given immutability
BigInteger and BigDecimal however to implement those methods
since they cannot perform boxing conversions.
*/
{
assert new Integer(1) + new Integer(2) == 3;
}
/*
# Compare wrappers
# Equality wrappers
Equality comparison `==` does *not* unbox them,
but because of the wrapper pool it works for some values.
< and > does.
*/
{
assert new Integer(1) != new Integer(1);
assert (new Integer(1)).equals(new Integer(1));
assert new Integer(1) < new Integer(2);
}
/*
# Void
TODO what is this used for?
<http://stackoverflow.com/questions/643906/uses-for-the-java-void-reference-type
*/
{
Void v;
// The only valid valud that can fit into a Void is null:
v = null;
}
/*
# NaN
*/
{
// http://stackoverflow.com/questions/8819738/why-does-double-nan-double-nan-return-false
// Basically because many unrealted operations can generate NaN,
// so comparing it does not make much sense.
assert Double.NaN != Double.NaN;
assert Double.isNaN(Double.NaN);
}
/*
# Integer wrapper
Wrapper for `int`.
*/
{
/*
# parseInt
*/
{
assert Integer.parseInt("123") == 123;
// Very strict. No whitespaces or other noise.
boolean fail = false;
try {
Integer.parseInt("123\n");
} catch (NumberFormatException e) {
fail = true;
}
assert fail;
}
}
}
}