Promotion in Java?

Viewed 18824

The rules for promotion is "when operands are of different types, automatic binary numeric promotion occurs with the smaller operand type being converted to the larger". But the operands are of same type for example,

byte=byte+byte // Compile time error... found int..

So why is it so?

5 Answers

To understand this you should refer the 2 things:

Implicit Casting: byte (8 bit) -> short (16 bit) -> int (32 bit) -> float (32 bit) -> double (64 bit) char (16 bit) -> int (32 bit)

Arithmetic Operator Rules

  1. Operator Precedence Rule : This rule states that Group of (*,/, %) will be evaluated first. Then Group of (+,-) operator will be evaluated. From a same Group of Operators, calculate from the left.

  2. Operand Promotion Rule : This rule states that Operands having data type smaller than int will be promoted to int. order of promotion (byte->short->int, char->int)

  3. Same Type Operand Rule: This rule states that if both operands are int,long,float,double then the same type is carried to the result type. i.e. long+long => long , float + float => float, int+int => int

  4. Mix Type Operand Rule : Follow the order of Promotion (int->long->float->double) if any of the operand is from the above order then the smaller will be promoted to the bigger one and result will be calculated in bigger type. i.e. long + double => double , int + long => long

Related