I posted this question after reading the arithmetic promotion section in
Java 2 Cert. Study Guide, RHE. The book states "for unary operators, two rules apply, depending on the type of the single operand:
- If the operand is a byte, a short, or a char, it is converted to an int.
- Else if the operand is of any other type, it is not converted."
Furthermore, they have this as an example:
short s = 9;
int i = 10;
float f = 11.1f;
double d = 12.2;
if(++s * i >= f / d)
System.out.println(">>>>>");
else
System.out.println("<<<<<");
"With the rules in mind, it is possible to determine what really happens in the code example given at the beginning of this section:
1. The short s is promoted to an int and then incremented.
2. The result of step 1 (an int) is multiplied by the int i. Since both operands are of the same type, and that type is not narrower than an int, no conversion is necessary. The results of the multiplication is an int.
3. ...
4. ..."
If you change my code slightly to make s a byte, you will get a compile error:
class Testing {
public static void main(String[] args) {
//short s;
for(short i = 0; i<10; i++) {
byte s = 0;
s = i;
System.out.println(s);
}
}
}
compiler error - Incompatible type for =. Explicit cast needed to convert short to byte.
s = i;
The compiler is saying that i has not been converted to an int! Here is another example:
class Testing {
public static void main(String[] args) {
short i, s = 0;
s++;
i = s;
System.out.println("s = " + s);
System.out.println("i = " + i);
}
}
output is:
s = 1
i = 1
Did RHE get this wrong? I'm just scratching my head.