3

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
kaka
  • 597
  • 3
  • 5
  • 16

3 Answers3

1

The values of the variables don't matter. Their types matter. double is an 8 bytes types and float is a 4 bytes type. Hence, to multiply a double and a float, you promote the variable of the smaller type (float) to the larger type (double).

If you are multiplying a Double with a Float, they will be unboxed to double and float. In order to multiply a double with a float, the float would be promoted to double, and double multiplication would take place.

Since the result is stored in an Object, the double result will be boxed to a Double.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

"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

Darkwyng
  • 130
  • 1
  • 7
1

You have misunderstood what "larger" means in the phrase "the larger of the two data types". If it had said "the larger of the two values", then your understanding would have been correct.

A large data type is one that takes up more memory. A double takes up 64 bits, while a float takes up 32 bits, so double is the larger data type.

Note that this behaviour (binary numeric promotion) only applies to numeric types and can't really be described with one single rule such as "If two values have different data types, Java will automatically promote one of the values to the larger of the two data types". For example, a short times a byte gives you an int. This is specified fully in the Java Language Specification.

For more info, see section 5.6.2 in the Java Language Specification.

Sweeper
  • 213,210
  • 22
  • 193
  • 313