Why Byte and Short type exceed their limit in java? How to overcome this?

317 Views Asked by At

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?

0

There are 0 best solutions below