0

In Java Integer and Long data type does not exceed their limit.

System.out.println("Min Integer Value: " + Integer.MIN_VALUE);
System.out.println("Max Integer Value: " + Integer.MAX_VALUE);
System.out.println("Busted Min Integer Value: " + (Integer.MIN_VALUE - 1));
System.out.println("Busted Max Integer Value: " + (Integer.MAX_VALUE + 1));

System.out.println("Min Long Value: " + Long.MIN_VALUE);
System.out.println("Max Long Value: " + Long.MAX_VALUE);
System.out.println("Busted Min Long Value: " + (Long.MIN_VALUE - 1));
System.out.println("Busted Max Long Value: " + (Long.MAX_VALUE + 1));

Output:

Min Integer Value: -2147483648
Max Integer Value: 2147483647
Busted Min Integer Value: 2147483647
Busted Max Integer Value: -2147483648

Min Long Value: -9223372036854775808
Max Long Value: 9223372036854775807
Busted Min Long Value: 9223372036854775807
Busted Max Long Value: -9223372036854775808

But Short and Byte go over their limit.

System.out.println("Min Short Value: " + Short.MIN_VALUE);
System.out.println("Max Short Value: " + Short.MAX_VALUE);
System.out.println("Overflow Min Short Value: " + (Short.MIN_VALUE - 5));
System.out.println("Overflow Max Short Value: " + (Short.MAX_VALUE + 10));

System.out.println("Min Byte Value: " + Byte.MIN_VALUE);
System.out.println("Max Byte Value: " + Byte.MAX_VALUE);
System.out.println("Overflow Min Byte Value: " + (Byte.MIN_VALUE - 5));
System.out.println("Overflow Max Byte Value: " + (Byte.MAX_VALUE + 10));

Output:

Min Short Value: -32768
Max Short Value: 32767
Overflow Min Short Value: -32773
Overflow Max Short Value: 32777

Min Byte Value: -128
Max Byte Value: 127
Overflow Min Byte Value: -133
Overflow Max Byte Value: 137

Why short and byte behave like that?

How to overcome this problem?

Mahbub Ul Islam
  • 773
  • 8
  • 15
  • 6
    Because Java arithmetic operators promote their operands to `int` or `long`. So what you are actually seeing is equivalent to (for example) `((int) Byte.MIN_VALUE) - 5` ... which does not overflow `int`. – Stephen C Dec 30 '21 at 07:37
  • @user16320675 - I think that that is the opposite of what the OP means by "exceeding the limit". The result will be `-128` which in the OP's sense is still within the limit of `byte`. Look carefully at the OP's examples to understand what the question is asking. – Stephen C Jan 02 '22 at 07:38
  • 1
    @Mahub - How to overcome it? Cast the result to a `byte` or `short`. Or use `+=`, `-=` and so on. – Stephen C Jan 02 '22 at 07:42

0 Answers0