- 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
Assigning long values carefully in java to avoid overflown
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.
- Related Articles
- Assigning values to static final variables in java\n
- Java Program to subtract long 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
- Assigning Values to Variables in Python
- Buffer Overflow Attack: Definition, Types, How to Avoid
- Assigning values to a computed property in JavaScript?
- Assigning arrays in Java.
- Values of CSS overflow property
- Create BigDecimal Values via a long in Java
- Overflow of DataTypes in Java
- Java overflow and underflow
- MySQL query to avoid displaying duplicates values?
- Java Program to get the maximum of three long values
- Java program to get the minimum of three long values
