Breaking News
Home / Java / Java FAQ / Int Overflow in Java

Int Overflow in Java

Integer Overflow JavaInteger overflow – sound familiar, isn’t it. This is one of the things every developer must have experience at least once during programming lifespan. Its a very common design flaw that acts as an silent killer and will crash the application/transaction or lead to erroneous result once overflows. So what is a actually a overflow? Simply put it, its when you are trying to put a larger or smaller value into a variable then what it can accept.

When you declare a variable of a given data type say int, the maximum and minimum value that can put into this variable is limited by its data type. The max and min value of int data type in Java is, 2^31-1 or (2147483647) and  -2^31 or (-2147483648) resp. <!>

The max and min value is defined as a constant in JDK as seem by the below snippet.

  1. public class IntLimits {
  2.  
  3.   public static void main(String[] args) {
  4.    
  5.     System.out.println("Max int value " + Integer.MAX_VALUE);  
  6.  
  7.     System.out.println("Min int value " + Integer.MIN_VALUE);  
  8.  
  9.   }
  10. }

Use-cases

Some of the very common use-cases where this issue exhibits is, the use of int datatype to store the value of sequence retrieved from the database to be used as unique id for a given transaction using JDBC. Generally the sequence starts from a smaller number and every time we get the nextval from the the sequence, it increases it value by 1. So depending on the volume of the transactions one day the sequence value will cross the max int value and this will cause an int overflow , resulting into error. So whenever dealing with sequences which can run into high numbers make sure you use a long data type instead.

[pb_builder]

Check Also

When is OCAJP Java certification going live?

After completing the BETA phase of testing last year, the Oracle’s new OCAJP Java certification, …

Advertisment ad adsense adlogger