May 05, 2018 Core Java, Examples, Snippet comments

Int or Integer is one of the common data type that we will encounter in Java since most programming involves calculations, and integers are the most basic numbers we could manipulate. We should take note however that Integers can't have arbitrarily large value. In fact it has a maximum value. The Java Integer Max Value is 2,147,483,647. Below are some more details to explain this.

### Explanation for Integer Max Value

Integers in Java is represented in 32 bits, so the upper limit of Integer value is capped by what this number of binary digits can hold. Since Integers can hold both negative and positive values, around 31 bits combinations represents the negative number spectrum, while another 31 bits holds the value range from 0 and positive values. So since 0 is included in the other side of the spectrum, the maximum value Integer can hold is 2 raised to the power of 31 minus 1. We need to do the minus one to account for the number 0. While the lowest negative value is minus 2 raised to the power of 31.

So 2 raised to the power of 31 is 2,147,483,648 which is expectedly an even number. And deducting one will bring the value 2,147,483,647 - which is the maximum value for integers.

As of the time of this writing, here is a code snippet from the Integer class that defines the constant maximum value of Integer in Java:

public final class Integer extends Number implements Comparable<Integer> {
...
/**
* A constant holding the maximum value an {@code int} can
* have, 2<sup>31</sup>-1.
*/
@Native public static final int MAX_VALUE = 0x7fffffff;
...
}

Since we have this constant, we don't need to remember the value 2,147,483,647. We can just use the constant Integer.MAX_VALUE to get the maximum Integer value in Java. Here is an example code for it's usage:

/**
* A simple application that looks up the value of Integer.MAX_VALUE and outputs it to the user.
**/
public class Test
public static void main(String[] args) {
System.out.println("The maximum Integer value is: "+Integer.MAX_VALUE);
}
}

The result of this code is this:

The maximum Integer value is: 2147483647

Now what happens if we try to add the value 1 to this number? For example:

/**
* A simple application that tries to add the value 1 to the maximum integer value:
*/
public class Test2 {
public static void main(String[] args) {
int maxIntValue = Integer.MAX_VALUE;
maxIntValue = maxIntValue + 1;
System.out.println("The maximum Integer value plus one is: " + maxIntValue);
}
}

Surprisingly, we will get the lowest negative number. Here is the output of the code:

The maximum Integer value plus one is: -2147483648