六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 123|回复: 0

Operators and Assignments

[复制链接]

升级  29.33%

26

主题

26

主题

26

主题

秀才

Rank: 2

积分
94
 楼主| 发表于 2013-2-7 20:18:57 | 显示全部楼层 |阅读模式
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 floatRemember 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
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表