Assigning long values carefully in java to avoid overflow

Java Programming Java8Object Oriented Programming

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.


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;

      //Scenario 2:  
      //Assigning long value causing no overflow
      MICROSECONDS_A_DAY = 24L * 60 * 60 * 1000 * 1000;




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.

Published on 23-Jul-2018 08:47:55