Search code examples
javatype-promotion

Promotion in java


I exectued this statement

System.out.println(3.0 + 5/2); 

And found the answer to be 5.0. Now according to promotion, if an expression contains a double type data, every operand will be promoted to double type. So 5 and 2 will be promoted to 5.0 and 2.0 respectively. Therefore the logical expression here should be

3.0+5.0/2.0

Which should give the answer 5.5 instead of 5.0.


Solution

  • It's important to remember the order of operations!

    3.0 + 5/2
    3.0 + (5/2)
    3.0 + 2
    3.0 + 2.0
    5
    

    5/2 executes first, giving back 2.

    Hope this helps!