-1

I'm taking an intro to Java class that asks the following question:

Select the primitive type of this expression's result: 32.0 % 6 choices: int, float, double, long

I chose float, but the correct answer is double. I don't understand; 32.0 % 6 = 2.0, which falls within the ranges of both float and double. Why is one right and the other wrong?

The explanation given is "The 6 is promoted from an int to a double, which then leads to a double result."

  • 1
    Have a look at https://stackoverflow.com/questions/5076710/what-is-float-in-java – Scary Wombat May 10 '22 at 23:44
  • 6
    Because 32.0 is a `double`. And when you do mathematical operations with a `double`, you end up with a `double`. – Dawood ibn Kareem May 10 '22 at 23:52
  • The int promotion isn't very relevant here. Even if you could divide a double by an int, the result would presumably be double. – shmosel May 11 '22 at 00:05
  • 1
    @ruakh Cannot see the connection with your alleged duplicate. – user207421 May 11 '22 at 00:14
  • 2
    As per the [JLS](https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.2): *A floating-point literal is of type `float` if it is suffixed with an ASCII letter `F` or `f`; otherwise its type is `double` and it can optionally be suffixed with an ASCII letter `D` or `d`* – Bohemian May 11 '22 at 00:28
  • @user207421: The connection is that they have the same basic question ("why is this a double instead of a float?") and the same answer ("because floating-point literals are doubles unless they end in `f`"). – ruakh May 11 '22 at 05:21

1 Answers1

2

In Java, a floating point literal that is not terminated by the character "f" is a double. That includes the literal 32.0.

A modulo applied to a double will result in a double, hence the answer is double.

1.0 is a double even though it fits comfortably in a float. If you try something like float x = 1.0;, you will get an error that says incompatible types: possible lossy conversion from double to float. But if you do float x = 1.0f;, everything will be OK.

There are rules for how types are promoted. The rule of thumb is, the result of an expression will be the widest type or an error. In your case, everything becomes a double.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264