If two values have different data types, Java will automatically promote one of the values to the larger of the two data types?

kaka :

The rule says that if two values have different data types, Java will automatically promote one of the values to the larger of the two data types?

In the code below, the value assigned to y is larger than the value of x. Therefore, taking the rule into consideration, the printed value should be "Float" but instead it printed "Double. Can you please why it prints Double instead of Float?

    Double x = 3.21; 

    Float y = 4.1f;

    Object o  = (x*y);

    System.out.println( o.getClass().getSimpleName() ); // prints out Double
Darkwyng :

"Larger" does not refer to the ">" value, but (in a nutshell) to the data type that can hold more information, e.g. Double is preferred over Float and Long is preferred over Int.

This is documented here: https://docs.oracle.com/javase/specs/jls/se13/html/jls-5.html#jls-5.6.2

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=18253&siteId=1
Recommended