- 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 add integers and check for overflow
To check for Integer overflow, we need to check the Integer.MAX_VALUE with the added integers result, Here, Integer.MAX_VALUE 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 a = 9897988; int b = 8798798; System.out.println("Value1: "+a); System.out.println("Value2: "+b); long sum = (long)a + (long)b; if (sum > Integer.MAX_VALUE) { throw new ArithmeticException("Integer Overflow!"); } // displaying sum System.out.println("Sum: "+(int)sum); } }
Output
Value1: 9897988 Value2: 8798798 Sum: 18696786
In the above example, we have taken the following two integers.
int val1 = 9897988; int val2 = 8798798;
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 an exception is thrown.
If (sum > Integer.MAX_VALUE) { throw new ArithmeticException("Overflow!"); }
Advertisements