๐งช Unit Test 003: Data Overflow and Underflow โ
๐ Preface โ
Java's primitive data types have fixed sizes and cannot automatically detect when arithmetic operations exceed their bounds. This can result in overflow (exceeding the upper limit) or underflow (dropping below the lower limit), causing silent and often unexpected wrapping of values.
๐ฌ Test Case โ
java
public class T_003_DataOverflow {
@Test
public void test() {
int number = Integer.MAX_VALUE;
Assertions.assertEquals(2147483647, number); // 2147483647
Assertions.assertEquals(-2147483648, number + 1); // -2147483648
Assertions.assertEquals(-2, number + number);
}
}๐ Why This Matters โ
Overflow and underflow do not raise errors in Java, instead they silently wrap around. This can lead to subtle bugs in financial calculations, counters, or loops. Developers should use care when working near data type boundaries and consider tools like Math.addExact() to catch overflow at runtime.