0

I am trying to check if a long integer is greater than the INTEGER.MAX value but it's not working. It's very straight forward so I am just wondering if there is some problem with comparing an Integer object with a long as I have done because otherwise I don't know what the problem is. At the moment when the nextTotal value exceeds INTEGER.MAX, it kicks into negative numbers instead of printing the error message.

public Integer initialValue=0;

int amount = Integer.parseInt(amountStr);
        System.out.println("Received from client: " + amount);

        long nextTotal=amount+initialValue;
            if((nextTotal>Integer.MAX_VALUE)||    (nextTotal<Integer.MIN_VALUE)){
                System.out.println("Error: Integer has not been added as the total exceeds the Maximum Integer value!");
                out.flush();
            }  

            else{
                initialValue+=amount;
                out.println(initialValue); //server response
                System.out.println("Sending total sum of integers to the client:"+initialValue);
                out.flush();
                }
            }
0

2 Answers 2

2

The problem is that you have added two ints, but they haven't been promoted to long yet, so it overflows before being converted to a long, and of course an int can never be greater than Integer.MAX_VALUE. It will only get converted to a long upon assignment, which is after the addition.

Convert to a long before the addition, with a cast.

long nextTotal = (long) amount + initialValue;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help-I figured it was something simple!
0

Since you don't really want to use a long value, I would normally do the check like this:

int amount = Integer.parseInt(amountStr);
if (amount > (Integer.MAX_VALUE - initialValue)) 
  throw new IllegalArgumentException("Amount exceeds maximum value");
initialValue += amount;

In other words, check whether the amount will overflow before adding, and throw an exception (or send an error message or whatever is appropriate for your application) instead of proceeding normally.

Comments

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.