Share & learn

Through Innovative Digital Library

What is underflow in Java?

Explain about underflow in Java and how to prevent it?


Posted by Paul on April 26th 2018 10:08 AM

Underflow in Java : Underflow is a condition where the decided limit for particular data types is crossed. In case if underflow occurs, the program either crashes or unexpected outputs will be displayed, depending on how a language handles things. Underflow int operators : In Java, integer operations are performed in 32 bit precision. When an integer arithmetic operation (such as addition with integer operands) generates a result that cannot fit into these bits, the operation is said to underflow (exceed the smallest negative value that can be stored). Here is example for underflow in Java :

// Java code to demonstrate underflow
public class UnderflowDemo {

    public static 
void main(String[] args) {
// TODO Auto-generated method stub

        // roll over effect to upper limit in underflow
int underflowExample = -2147483648;
System.out.println("Underflow: " + (underflowExample 1));

double d 1e308;
System.out.println("*10= " 120);
// gradual underflow
1e-305 Math.PI;
System.out.print("gradual underflow: " "\n      ");
        for (
int i 04i++)
System.out.print(" " + (/= 100000));


Posted by Paul on April 26th 2018 10:09 AM

integer operators from Java don't detect underflow. Here is a code to check for potential underflow.

// check underflow in Java
public class PreventUnderflow {
    public static 
void main(String[] args) {
int amount = -30;
int total 0;

total += amount;
        if ((
amount total) < 0)
            throw new 
ArithmeticException("integer underflow occurred");
System.out.printf("Total: %d%n"total);

Answer Question

Your email address will not be published. Required fields are marked *

  • Minimum 20 character

related questions

Most liked questions

Most answered questions

W5J4 Refresh
W5J4 Refresh
Forgot password
Ask a Question
Minimum 20 character
Minimum 20 character
Minimum 20 character
W5J4 Refresh