- 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 multiply long integers and check for overflow
To check for Long overflow, we need to check the Long.MAX_VALUE with the multiplied long result, Here, Long.MAX_VALUE is the maximum value of Long type in Java.
Let us see an example wherein long values are multiplied and if the result is 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 = 6999; long val2 = 67849; System.out.println("Value1: "+val1); System.out.println("Value2: "+val2); long mul = val1 * val2; if (mul > Long.MAX_VALUE) { throw new ArithmeticException("Overflow!"); } // displaying multiplication System.out.println("Multiplication Result: "+(long)mul); } }
Output
Value1: 6999 Value2: 67849 Multiplication Result: 474875151
In the above example, we have taken the following two integers.
long val1 = 6999; long val2 = 67849;
Now we will multiply.
long mul = val1 * val2;
If the result is more than the maximum value, then an exception is thrown.
If (mul > Long.MAX_VALUE) { throw new ArithmeticException("Overflow!"); }
- Related Articles
- Java Program to multiply integers and check for overflow
- Java Program to add long integers and check for overflow
- Java Program to subtract long integers and check for overflow
- Java Program to add integers and check for overflow
- Java Program to subtract integers and check for overflow
- Java Program to check for Integer overflow
- Assigning long values carefully in java to avoid overflow\n
- Java Program to Check Armstrong Number between Two Integers
- Check for Integer Overflow in C++
- Explain how to multiply and divide integers.
- Check for integer overflow on multiplication in C++
- Java overflow and underflow
- Java program to multiply two matrices.
- Java Program to concatenate a String and Integers
- Java Program to concatenate Integers and a String

Advertisements