Following java program will compare customer balance with minimum balance. If customer balance is higher than minimum balance then customer will get a special discounts.
//Integer overflow & underflow exampleint min_balance = 25000;
int cust_balance = (25000 * 25000 * 20);
cust_balance = (-25000 * 25000 * 20);if (cust_balance >= min_balance)
{
System.out.println("This customer qualifies for special pricing.\n");
}
else
{
System.out.println("This customer does NOT qualify for special pricing\n");
}
Try giving 25, 25000, 30000 as customer balance, the program will behave as expectedly.
If you change the customer balance to the following computations, you will observer un expected behaviour in the program due to integer/overflow underflow.
cust_balance = (25000 * 25000 * 20); //Integer overflow
cust_balance = (-25000 * 25000 * 20); //Integer underflow
What happend:
Java does not detect errors in numerical computations at compile time. Java type "int" is represented as a 32-bit binary number. With 32 bits, it's possible to represent a little over four billion different values. The values of type int range from -2147483648 to 2147483647.
When the result of a computation lies outside this range, the mathematically correct result in each case cannot be represented as a value of type int. The above two computations lies outside of the range. These are examples of integer overflow/underflow.
In most cases, integer overflow/overflow should be considered an error. However, Java does not automatically detect such errors.