Skip to content

Commit 34a42c5

Browse files
committed
StrictMath and unsigned ints
1 parent 83ded37 commit 34a42c5

File tree

2 files changed

+57
-18
lines changed

2 files changed

+57
-18
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package com.winterbe.java8.samples.misc;
2+
3+
/**
4+
* @author Benjamin Winterberg
5+
*/
6+
public class Math1 {
7+
8+
public static void main(String[] args) {
9+
testMathExact();
10+
testUnsignedInt();
11+
}
12+
13+
private static void testUnsignedInt() {
14+
try {
15+
Integer.parseUnsignedInt("-123", 10);
16+
}
17+
catch (NumberFormatException e) {
18+
System.out.println(e.getMessage());
19+
}
20+
21+
long maxUnsignedInt = (1l << 32) - 1;
22+
System.out.println(maxUnsignedInt);
23+
24+
String string = String.valueOf(maxUnsignedInt);
25+
26+
int unsignedInt = Integer.parseUnsignedInt(string, 10);
27+
System.out.println(unsignedInt);
28+
29+
String string2 = Integer.toUnsignedString(unsignedInt, 10);
30+
System.out.println(string2);
31+
32+
try {
33+
System.out.println(Integer.parseInt(string, 10));
34+
}
35+
catch (NumberFormatException e) {
36+
System.out.println("could not parse signed int of " + maxUnsignedInt);
37+
}
38+
}
39+
40+
private static void testMathExact() {
41+
System.out.println(Integer.MAX_VALUE + 1);
42+
43+
try {
44+
Math.addExact(Integer.MAX_VALUE, 1);
45+
}
46+
catch (ArithmeticException e) {
47+
System.out.println(e.getMessage());
48+
}
49+
50+
try {
51+
Math.toIntExact(Long.MAX_VALUE);
52+
}
53+
catch (Exception e) {
54+
System.out.println(e.getMessage());
55+
}
56+
}
57+
}

src/com/winterbe/java8/samples/misc/StrictMath1.java

Lines changed: 0 additions & 18 deletions
This file was deleted.

0 commit comments

Comments
 (0)