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

你可能感兴趣的:(html)