However, Java has no unsigned int (yet). So what does it mean "Char acts as unsigned integer in arithmetic operations"?
Originally posted by Joseph Sweet:
Sounds strange. According to what you say, within an arithmetic operation, the char is automatically cast to an "unsigned" int which its positive range is LARGER than a regular ("signed") int's (2^32 - 1 vs. 2^31 - 1).
Not quite. The unsigned char value (16 bits) is widened to a signed int value (32 bits).
The char's unsigned value in the range of 0 through 2^16 - 1 fits easily into the signed int's range of -2^31 through 2^31 - 1. But there is never actually an unsigned int, nor a value that would exceed the signed int's maximum.
Does that make sense?
Therefore, in an arithmetic operation, a char acts as a positive int
Well it was a somewhat ambiguous statement. After the conversion (adding two zero MS bytes), it starts as a positive int, but it does not "act" as a positive int. The arithmetic operation can result in a negative int.
Ok. That was strange of them to present char arithmetic as a special case, since they have already presented earlier the general rules which are:
The Java VM specification states the following rules for promotion in an expression of two operands, as in x+i:
If either operand is of type double, the other is converted to double.
Otherwise, if either operand is of type float, the other is converted to float.
Otherwise, if either operand is of type long, the other is converted to long.
Otherwise, both operands are converted to type int.
Which answers my original question pretty well. So same rule applies to short, byte.... right?
As for boolean arithmetic, I don't know. I am not sure how they are represented in memory.
Unlike in C where you can say if (c = 1) d = 2; else d = 3; thereby getting yourself three errors for the price of one, you cannot mix Boolean values and numbers. There is no use of 1 = true and 0 = false. The only vague approach to it I have ever seen in Java is that the %b flag prints "true" for any non-null value and "false" for nulls.
Also, the rule that I cited above seems to apply then only to number, where chars and bytes are also considered as numbers for that matter.
[ July 07, 2007: Message edited by: Joseph Sweet ]
Apart from that, one just has to guess how booleans values are stored.