Share & learn

Through Innovative Digital Library

What is overflow in Java?

Explain about overflow in Java and how to prevent it?
 



Answers

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

Overflow in Java : Overflow is a condition where the decided limit for particular data types is crossed. If overflow occurs, the program either crashes or unexpected outputs will be displayed, depending on how a language handles things. Overflow 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 overflow. Here is example for overflow in Java :

// Java code to demonstrate overflow
public class OverflowDemo {

    public static 
void main(String[] args) {
        
// TODO Auto-generated method stub
        
        // roll over effect to lower limit in overflow
        
int overflowExample 2147483647;
        
System.out.println("Overflow: " + (overflowExample 1));

        
double d 1e308;
        
System.out.println("*10= " 10);
        
    }

}

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

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

// check overflow in java
public class PreventOverflow {

    public static 
void main(String[] args) {
        
// TODO Auto-generated method stub
        
int amount 30;
        
int total 0;
        
// int total = Integer.MAX_VALUE;
        
total += amount;
        
        
// exception to check for overflow.
        
if ((amount total) < 0)
            throw new 
ArithmeticException("integer overflow occured");
        
System.out.printf("Total: %d%n"total);
    }

}
Answer Question

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

  • Minimum 20 character
QL0H

related questions

Most liked questions

Most answered questions

Login
QL0H Refresh
Register
QL0H Refresh
Forgot password
Ask a Question
Minimum 20 character
Minimum 20 character
Reply
Minimum 20 character
QL0H Refresh