0

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 ?

2
  • you might need it to check if an integer addition might get to create an overflow. It´s also a nice initializer if you want to find the max and min values in an array of int´s Commented Jan 19, 2016 at 7:33
  • Can't you check how this return value is used in the code? Why do yo need to guess? Commented Jan 19, 2016 at 7:44

2 Answers 2

3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

i´d add to this that valueToAdd should definitely be >= 0, otherwise this condition could be true and could still create an overflow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.