To find Integers (or primitive int datatype) max and min values you can print use of the Integer wrapper class Integer.MAX_VALUE and Integer.MIN_VALUE constant values.
You can see that these are defined as static final values as hexadecimal values in java.lang.Integer class.
/**
* A constant holding the minimum value an int can have, -231.
*/
@Native
public static final int MIN_VALUE = 0x80000000;
/**
* A constant holding the maximum value an int can have, 231-1.
*/
@Native
public static final int MAX_VALUE = 0x7fffffff;
Example:
package org.code2care.java.examples;
public class Main {
public static void main(String[] args) {
int intMaxValue = Integer.MAX_VALUE;
int intMinValue = Integer.MIN_VALUE;
System.out.println("int/Integer Min Value in Java: " + intMinValue);
System.out.println("int/Integer Max Value in Java: " + intMaxValue);
}
}
Output:
Caution with Integer Overflow and Underflow issues
Be very careful when working with them, as you can end up with overflow and underflow issues which are hard to debug at times.
Overflow Example:
int intMaxValuePlusOne = Integer.MAX_VALUE + 1;
System.out.println(Integer.MAX_VALUE +" + 1 = "+ intMaxValuePlusOne);
int intMaxValuePlusOne = Integer.MAX_VALUE + 1;
System.out.println(Integer.MAX_VALUE +" + 1 = "+ intMaxValuePlusOne);As you can see when I just add 1 to the integers max value, we get an unexpected answer. This is called overflow.
Underflow Example:
int intMinValuePlusOne = Integer.MIN_VALUE + 1;
System.out.println(Integer.MAX_VALUE +" - 1 = "+ intMinValuePlusOne);
int intMinValuePlusOne = Integer.MIN_VALUE + 1;
System.out.println(Integer.MAX_VALUE +" - 1 = "+ intMinValuePlusOne);As you can see when I just subtract 1 from the integer's min value, we get an unexpected answer. This is called underflow.
To avoid make sure you know the range of the values you are dealing with, or make use of subtractExact() and addExact() static methods form java.math package that was added in Java 8 to deal with underflow and overflow issues.
Example:
Integer intMinValueMinusOne = Math.subtractExact(Integer.MIN_VALUE, 1);
System.out.println(Integer.MIN_VALUE +" - 1 = "+ intMinValueMinusOne);
That's better! You can simply add a try-catch block and handle it accordingly.
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!