When Overflow of DataTypes occur in Java

When a value more than the Maximum value of a datatype is assigned, it leads to Overflow. Java handles overflow of  datatypes on its own, for example, if we will increment 1 to Integer.MAX_VALUE, an error won’t be visible. However, the output will be Integer.MIN_VALUE.

Let us now see some examples displaying how Java handles overflow of datatypes:

Example 1

The code shows how Java handles overflow of int datatype:

public class Example {

  public static void main(String[] args) {
    
    System.out.println("int type MAXIMUM Value = " + Integer.MAX_VALUE);
    System.out.println("int type MINIMUM Value = " + Integer.MIN_VALUE);
    
    System.out.println("\nOn incrementing, the result is equivalent to integer's minimum value...");

    System.out.println("\nIncrementing Integer Maximum Value = " + (Integer.MAX_VALUE+1));
  }
}

Output

int type MAXIMUM Value = 2147483647
int type MINIMUM Value = -2147483648

On incrementing, the result is equivalent to integer's minimum value...

Incrementing Integer Maximum Value = -2147483648

Example 2

The code shows how Java handles overflow of long datatype:

public class Example {

  public static void main(String[] args) {
    
    System.out.println("long type MAXIMUM Value = " + Long.MAX_VALUE);
    System.out.println("long type MINIMUM Value = " + Long.MIN_VALUE);
    
    System.out.println("\nOn incrementing, the result is equivalent to long's minimum value...");

    System.out.println("\nIncrementing long Maximum Value = " + (Long.MAX_VALUE+1));
  }
}

Output

long type MAXIMUM Value = 9223372036854775807
long type MINIMUM Value = -9223372036854775808

On incrementing, the result is equivalent to long's minimum value...

Incrementing long Maximum Value = -9223372036854775808

However, this is not the case with any other datatype. Let’s see another example wherein we are multiplying the Maximum value of Float type:

Example 3

public class Example {

  public static void main(String[] args) {
    
    System.out.println("float type MAXIMUM Value = " + Float.MAX_VALUE);
    System.out.println("float type MINIMUM Value = " + Float.MIN_VALUE);

    System.out.println("\nUpdating Float Maximum Value = " + (Float.MAX_VALUE*5));
  }
}

Output

float type MAXIMUM Value = 3.4028235E38
float type MINIMUM Value = 1.4E-45

Updating Float Maximum Value = Infinity

In the above output, we are getting Infinity i.e. Overflow since we exceeded the maximum value of Float Datatype in Java.

Java Programming Examples
Understanding Boolean Type in Java with examples
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment