Operators and Assignments - Numeric Promotion

copy from  http://www.janeg.ca/scjp/oper/promotions.html#unary

 

Operators and Assignments - Numeric Promotion

Unary Numeric Promotion

  • the Unary operators + and - when applied to byte, char or short numeric types result in the operand being automatically promoted to an int.(JLS §5.6.1)
    Example producing compile error:
    
        byte b  = 5;         // assign byte value
        byte b1 = +b;        // found int, required byte 
    
  • unary promotion also applies for all shift operators. A long operator does not force the conversion of a left-hand int operator to long(JLS§5.6.1)

Binary Numeric Promotion

  • when operands are of different types, automatic binary numeric promotion occurs with the smaller operand type being converted to the larger.
  • the following rules are applied in the order given. (JLS §5.6.2)
    • if either operand is a double, the other operand is converted to double
    • otherwise, if one of the operands is a float, the other operand is converted to a float
    • otherwise, if one of the operands is a long, the other operand is converted to a long
    • otherwise, both operands are converted to int
Examples producing compile-errors:
    
    byte = byte + byte;         // found int, required byte
    int  = float + int;         // found float, required int
    long = float + long;        // found float, required long
    float = double + float;     // found double, required float

Remember to check the type of the variable to which results are assigned

Rules apply to following operators:

  • Additive: + and -
  • Multiplicative: *, /, and %
  • Comparison: <, <=, >, and >=
  • Equality: = and !=
  • Bitwise: &, ^, and |

Special case for Ternary conditional operator (JLS §15.25)

  • if one of the operands is byte and the other is short then the type of the expression is short
        byte = true ? byte : short // found short, required byte
    
  • if one of the operands is a constant of type int and the other operand has a type of byte, short, or char and the value of the int operand is within the other type range, the type of the expression will be the type of the non-int operand.
        short = true  ? short : 1000; // compiles and runs OK
        short = false ? short : 1000; // compiles and runs OK
    

Example Code

  • check attachment pls

Traps

  • expression assigning byte or short operations to a byte or short variable
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值