Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Primitive assignments - Strange behavior

 
Faisal Ahmad
Ranch Hand
Posts: 355
Chrome Java Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Faisal Ahmad
Ranch Hand
Posts: 355
Chrome Java Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
What about:

Why can't the compiler do the same here?
 
Faisal Ahmad
Ranch Hand
Posts: 355
Chrome Java Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic