简体   繁体   中英

Integer.MAX_VALUE in java

I have read about MAX_VALUE and found that a constant can hold a maximum value of 2^31-1. Where is the need to use a MAX_VALUE for any program?

I am also confused on this piece of stack code, where if the stack is empty it return Integer.Max_VALUE.

if(s2.isEmpty())
    return Integer.MAX_VALUE; 

Why should we return a max number when the stack is empty ?

Example usage of MAX_VALUE :

List<Integer> l = Arrays.asList(1, 2, 182938, 1293);
Integer min = Integer.MAX_VALUE;

for (Integer i : l) { 
     min = Math.min(min, i);
}

To be honest, I have hardly ever used this, but for one thing it is quite practical:

If you are searching for a minimum, you can inititally start with Integer.MAX_VALUE as it is guaranteed that the next value will be smaller.

The second use case scenario is to check if this variable can be used for any further calculations, by checking (var <= Integer.MAX_VALUE - valueToAdd && valueToAdd >= 0) beforehand.

Returning Integer.MAX_VALUE is nice if you certainly know that a number cannot possible be that high. I often use -1 as return value if an int cannot be negative, but if it can you need to think of something else, which would be using MAX_VALUE then.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM