
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Assign Long Values Carefully in Java to Avoid Overflow
In case of having the operation of integer values in Java, we need to be aware of int underflow and overflow conditions. Considering the fact that in Java, The int data type is a 32-bit signed two's complement integer having a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647. If a value goes beyond the max value possible, the value goes back to minimum value and continue from that minimum. In a similar way, it happens for a value less than the min value. Consider the following example.
Example
public class Tester { public static void main(String[] args) { //Scenario 1: //Assigning int value to long causing overflow long MICROSECONDS_A_DAY = 24 * 60 * 60 * 1000 * 1000; System.out.println(MICROSECONDS_A_DAY); //Scenario 2: //Assigning long value causing no overflow MICROSECONDS_A_DAY = 24L * 60 * 60 * 1000 * 1000; System.out.println(MICROSECONDS_A_DAY); } }
Output
500654080 86400000000
Points to be considered
Although we've used a long variable, the multiplication operation is int based in scenario 1 causing the int overflow. As a result, the output is incorrect.
In scenario 2, we enforced multiplication operation to belong based leading to a correct result.