Home  |   STIU  |   WOW  |   SCJP  |   SCDJWS   |   JEE FAQ  |   About US  |  

FAQ
  Java FAQ
  JSP FAQ
  Servlet FAQ
 

Advertisement

XyzWs Java FAQ:
What is numeric promotion?


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend


Previous Next vertical dots separating previous/next from contents/index/pdf Contents
Advertisement
XyzWs Java FAQ: What is numeric promotion?

What is numeric promotion?


5.6 Numeric Promotions in JLS:

Numeric promotion is applied to the operands of an arithmetic operator. Numeric promotion contexts allow the use of an identity conversion or a widening primitive conversion, or an unboxing conversion.

Numeric promotions are used to convert the operands of a numeric operator to a common type so that an operation can be performed. The two kinds of numeric promotion are unary numeric promotion and binary numeric promotion.

Example of unary numeric promotion produces compile error:

    byte b  = 15;         // assign byte value
    byte b1 = +b;        // result int but required byte. Compiler error 

This is covered by "if the operand is of compile-time type byte, short, or char, unary numeric promotion promotes it to a value of type int" by a widening conversion". You must explicit cast the value to byte type.

Examples of Binary Numeric Promotion produces compile-errors:

   
    byte = byte + byte;        // result int can not assign to variable's byte
                               // (covered by "both operands are converted to type int")
    int  = float + int;        // result float can not assign to variable's int 
                               // (covered by "if either operand is of type float, the other is converted to float")
    long = float + long;       // result float can not assign to variable's  long 
                               // (covered by "if either operand is of type float, the other is converted to float")
    float = double + float;    // result double can not assign to variable's float 
                               // (covered by "If either operand is of type double, the other is converted to double")

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

Support  | Feedback  | Help