Java – why a loop with a char because its index is infinite?
This cycle will continue indefinitely:
char a = 100; for(a=100; a>=0;--a) System.out.println(a);
Does this happen because a is promoted to the int value of the arithmetic operation and extends from the 16 bit char value to 32 bits, so it will always remain positive?
Solution
It does cycle indefinitely - you have a very similar reason This is because a cannot represent any number that does not satisfy > = 0 – char is unsigned Arithmetic underflow is clearly defined in Java and has no indication Please refer to the following relevant sections of the specification
> §4.2. two
This means that there is no sign of overflow / underflow other than the comparison value... For example, if a < = - A, underflow occurs. > §15.15. two
Therefore, we can see that there are two main steps: binary promotion, and then the initial conversion of reduction. > §5.6. two
We can see that the decrement expression uses what is considered an int to perform an extended conversion This allows it to represent the value - 1. > §5.1. three
Retaining only n lowest order bits means retaining only the lowest 16 bits of int expression A-1 Since - 1 is 0b111111111111111111111111111111111111111111111, only the lower 0b111111111111111111111111111111 is saved Since char is unsigned, all these bits contribute to the result, giving 65535
Notice what's here? In essence, this means that the Java integer algorithm is modular; In this case, the modulus is 2 ^ 16 or 65536 because char is a 16 bit data type- 1 (MOD 65536) ≡ 65535, so the decrement will wrap around