Hi, In RHE p 107 the following rules are given: unary operators: If the operand is a byte, short or char, it is converted to an int, If the operand is an int or larger it is not converted. However the following works.
If the ++ operator promotes to an int, why can I assign an int into s which is a short without any problems? Thanks for your help.
<a href="http://www.ajmasters.com" target="_blank" rel="nofollow">http://www.ajmasters.com</a> Real Estate, Tampa Florida
At run time, if evaluation of the operand expression completes abruptly, then the prefix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (�5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (�5.1.3) to the type of the variable before it is stored. The value of the prefix increment expression is the value of the variable after the new value is stored.
Hello Mario, I had asked the same doubt couple of weeks back: think abt this: char c='i'; c++; System.out.println(c); char c was not required to be cast to int, perform the ++, and cast back to char. THE POINT IS, for byte,short and char, you dont need to. also about the other point being discussed: short s=3; works but int i=3; short s=i; gives a compile time error. (possible loss of precision). This is because only in two cases the compiler performs implicit downcast. First, in an assignment like the one above(only works for int and lower order) another is the "op=" operator, where you can say byte b=0; b+=1; here b is promoted to an int, performed the +=1 and cast back to byte. Please correct me if I am wrong!! HTH,
Joined: Nov 01, 2000
Thanks guys, it all helps. I guess the example with a char really makes it clear why a promotion to int is necessary. With byte and short it is not very obvious. After all it is only adding 1, why would it needs a 32bit overhead to do that... but with char it makes some sense why it needs to promote to a common ground. The example with overflow is something else also. Funny how some much info is involved with those little ++
Thanks again, Mario
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com