- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to check for Integer overflow
To check for Integer overflow, we need to check the Integer.MAX_VALUE, which is the maximum value of an integer in Java.
Let us see an example wherein integers are added and if the sum is more than the Integer.MAX_VALUE, then an exception is thrown.
Example
public class Demo { public static void main(String[] args) { int val1 = 9898989; int val2 = 6789054; System.out.println("Value1: "+val1); System.out.println("Value2: "+val2); long sum = (long)val1 + (long)val2; if (sum > Integer.MAX_VALUE) { throw new ArithmeticException("Overflow!"); } // displaying sum System.out.println("Sum: "+(int)sum); } }
Output
Value1: 9898989 Value2: 6789054 Sum: 16688043
In the above example, we have taken the following two integers −
int val1 = 9898989; int val2 = 6789054;
Now we will cast and add them to a long.
long sum = (long)val1 + (long)val2;
If the result is more than the maximum value, then a exception is thrown.
if (sum > Integer.MAX_VALUE) { throw new ArithmeticException("Overflow!"); }
- Related Articles
- Check for Integer Overflow in C++
- Java Program to multiply integers and check for overflow
- Java Program to add integers and check for overflow
- Java Program to subtract integers and check for overflow
- Check for integer overflow on multiplication in C++
- Java Program to add long integers and check for overflow
- Java Program to multiply long integers and check for overflow
- Java Program to subtract long integers and check for overflow
- How to detect integer overflow in C++?
- How to detect integer overflow in C/C++?
- Java Program to Print a Square Pattern for given integer
- Java Program to Print an Integer
- Java Program to decode string to integer
- Java Program to convert integer to octal
- Java Program to convert integer to hexadecimal

Advertisements