- 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 subtract integers and check for overflow
To check for Integer overflow, we need to check the Integer.MAX_VALUE with the subtracted integers result, Here, Integer.MAX_VALUE is the maximum value of an integer in Java.
Let us see an example wherein integers are subtracted and if the result is more than Integer.MAX_VALUE, then an exception is thrown.
The following is an example showing how to check for Integer overflow.
Example
public class Demo { public static void main(String[] args) { int val1 = 9898999; int val2 = 8784556; System.out.println("Value1: "+val1); System.out.println("Value2: "+val2); long sub = (long)val1 - (long)val2; if (sub > Integer.MAX_VALUE) { throw new ArithmeticException("Overflow!"); } // displaying subtraction result System.out.println("Subtraction Result: "+(int)sub); } }
Output
Value1: 9898999 Value2: 8784556 Subtraction Result: 1114443
In the above example, we have taken the following two integers −
int val1 = 9898999; int val2 = 8784556;
Now we will cast and subtract them to a long.
long sub = (long)val1 - (long)val2;
If the result is more than the maximum value, then an exception is thrown.
If (sub > Integer.MAX_VALUE) { throw new ArithmeticException("Overflow!"); }
- Related Articles
- Java Program to subtract long integers and check for overflow
- Java Program to multiply integers and check for overflow
- Java Program to add integers and check for overflow
- Java Program to add long integers and check for overflow
- Java Program to multiply long integers and check for overflow
- Java Program to check for Integer overflow
- How to subtract integers?
- Java Program to Check Armstrong Number between Two Integers
- Check for Integer Overflow in C++
- Java program to subtract two matrices.
- How to add and subtract integers using number line?
- Check for integer overflow on multiplication in C++
- Java overflow and underflow
- Java Program to concatenate a String and Integers
- Java Program to concatenate Integers and a String

Advertisements