Skip to content

Commit 1657420

Browse files
Maiklinspivovarit
authored andcommitted
1 parent 7bbd585 commit 1657420

File tree

2 files changed

+92
-0
lines changed

2 files changed

+92
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package com.baeldung.overflow;
2+
3+
import java.math.BigInteger;
4+
5+
public class Overflow {
6+
7+
public static void showIntegerOverflow() {
8+
9+
int value = Integer.MAX_VALUE-1;
10+
11+
for(int i = 0; i < 4; i++, value++) {
12+
System.out.println(value);
13+
}
14+
}
15+
16+
public static void noOverflowWithBigInteger() {
17+
18+
BigInteger largeValue = new BigInteger(Integer.MAX_VALUE + "");
19+
for(int i = 0; i < 4; i++) {
20+
System.out.println(largeValue);
21+
largeValue = largeValue.add(BigInteger.ONE);
22+
}
23+
}
24+
25+
public static void exceptionWithAddExact() {
26+
27+
int value = Integer.MAX_VALUE-1;
28+
for(int i = 0; i < 4; i++) {
29+
System.out.println(value);
30+
value = Math.addExact(value, 1);
31+
}
32+
}
33+
34+
public static int addExact(int x, int y) {
35+
36+
int r = x + y;
37+
if (((x ^ r) & (y ^ r)) < 0) {
38+
throw new ArithmeticException("int overflow");
39+
}
40+
return r;
41+
}
42+
43+
public static void demonstrateUnderflow() {
44+
45+
for(int i = 1073; i <= 1076; i++) {
46+
System.out.println("2^" + i + " = " + Math.pow(2, -i));
47+
}
48+
}
49+
50+
public static double powExact(double base, double exponent)
51+
{
52+
if(base == 0.0) {
53+
return 0.0;
54+
}
55+
56+
double result = Math.pow(base, exponent);
57+
58+
if(result == Double.POSITIVE_INFINITY ) {
59+
throw new ArithmeticException("Double overflow resulting in POSITIVE_INFINITY");
60+
} else if(result == Double.NEGATIVE_INFINITY) {
61+
throw new ArithmeticException("Double overflow resulting in NEGATIVE_INFINITY");
62+
} else if(Double.compare(-0.0f, result) == 0) {
63+
throw new ArithmeticException("Double overflow resulting in negative zero");
64+
} else if(Double.compare(+0.0f, result) == 0) {
65+
throw new ArithmeticException("Double overflow resulting in positive zero");
66+
}
67+
68+
return result;
69+
}
70+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.baeldung.math;
2+
3+
import static org.junit.Assert.assertTrue;
4+
5+
import org.junit.Test;
6+
7+
public class OverflowUnitTest {
8+
9+
@Test
10+
public void positive_and_negative_zero_are_not_always_equal() {
11+
12+
double a = +0f;
13+
double b = -0f;
14+
15+
assertTrue(a == b);
16+
17+
assertTrue(1/a == Double.POSITIVE_INFINITY);
18+
assertTrue(1/b == Double.NEGATIVE_INFINITY);
19+
20+
assertTrue(1/a != 1/b);
21+
}
22+
}

0 commit comments

Comments
 (0)