- 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 long integers and check for overflow
To check for Long overflow, we need to check the Long.MAX_VALUE with the subtracted long result. Here, Long.MAX_VALUE is the maximum value of Long type in Java.
Let us see an example wherein long integers are subtracted and if the result is still more than the Long.MAX_VALUE, then an exception is thrown −
The following is an example showing how to check for Long overflow −
Example
public class Demo { public static void main(String[] args) { long val1 = 70123; long val2 = 10567; System.out.println("Value1: "+val1); System.out.println("Value2: "+val2); long diff = val1 - val2; if (diff > Long.MAX_VALUE) { throw new ArithmeticException("Overflow!"); } // displaying subtraction System.out.println("Subtraction Result: "+diff); } }
Output
Value1: 70123 Value2: 10567 Subtraction Result: 59556
In the above example, we have taken the following two integers −
long val1 = 70123; long val2 = 10567;
Now we will perform subtraction −
long diff = val1 - val2;
If the result is still more than the maximum value, then an exception is thrown −
If (diff > Long.MAX_VALUE) { throw new ArithmeticException("Overflow!"); }
Advertisements