Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Primitive assignments - Strange behavior

Ranch Hand
Posts: 355
Expressions invloving byte, short or int always result in an int value. Look into the following code:

Thanks!

Yogvinder Singh Ghotra
Ranch Hand
Posts: 38
For Unary increment and Decrement Operators

In the case where the operand is of type char, byte, or short, both binary numeric promotion and an implicit narrowing conversion are performed to achieve the side effect of modifying the value of the operand.

The side effect of incrementing the value of byte variable d requires binary numeric promotion to perform int addition, followed by an implicit narrowing conversion of the int value to byte.

[ September 18, 2007: Message edited by: Yogvinder Singh Ghotra ]
[ September 18, 2007: Message edited by: Yogvinder Singh Ghotra ]

Ranch Hand
Posts: 355
Thanks!
Thats clear for unary increment/decrement operations. Compiler automatically promotes the value to int and after the operation, narrows it down to fit into the range.

Why can't the compiler do the same here?

Ranch Hand
Posts: 355
Something that I found in JLS:
When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value of a numeric type, the following rules apply, in order, using widening conversion (�5.1.2) to convert operands as necessary:

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.

Yogvinder Singh Ghotra
Ranch Hand
Posts: 38
Simply stated

Binary Numeric Promotion:
If T is broader than int, both operands are converted to T; otherwise, both operands are converted to int.

Gavin Tranter
Ranch Hand
Posts: 333
is it not the case that there is no narrowing, but that promotion (cast) to int is actual happening.

So what is actual happening is you are trying to assign an int to a byte, which will never work.

where as when you use += and ++ there is an impliccit narrow from the int result to the byte operand (as stated in above posts)

Just my two pence
G