Search code examples
javafor-loopintegerbyteprimitive

Why Java did not check for type compatibility for byte as it does with int?


I am trying to use byte as control loop variable in for loop. I used the condition as n < 128 (where 128 is out of range of byte)

for (byte n =0; n < 128 ; n++) System.out.println("I am in For loop. "+ n ); 

The loop is going infinitely from 0 to 127 and then -128 to 127.

When I tried to do the same with int, it gave an error.

for (int n = 0; n < 2147483648; n++)

The literal 2147483648 of type int is out of range

Why did Java not check the type compatibility with byte like it checked for int?


Solution

  • The type compatibility is not checked against the type of the loop's variable.

    The type of an integer literal with no suffix is always int. 128 is a valid int, so the first loop passes compilation but results in numeric overflow leading to an infinite loop.

    On the other hand, 2147483648 is not a valid int, so the second loop doesn't pass compilation. If you replace 2147483648 with a long literal (2147483648L), the second loop will also pass compilation.