Assigning 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

Live Demo

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.

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 18-Jun-2020

181 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements