Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

floating point - Representing float values in Java

Look at the three lines of code below.

  float f = 1;

  float g = 1.1;

  float h = 1.1f;

Second line has compilation errors, while the other lines do not have compilation errors. First line is working fine without suffix f and third line is working with suffix f. Why is this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Floating point literals in Java is a double value by default.

JLS 3.10.2 Floating-Point Literals

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.

You can't assign a double value to a float without an explicit narrowing conversion. You therefore have two options:

  • For literals, use the suffix f or F to denote a float value
  • For non-literals, use an explicit cast (float)

An example of the latter is:

double d = 1.1;
float f = (float) d; // compiles fine!

On widening conversions

The reason why this compiles:

float f = 1;

is because the widening conversion from int to float can be done implicitly in the context of an assignment.

JLS 5.2 Assignment Conversion

Assignment conversion occurs when the value of an expression is assigned to a variable: the type of the expression must be converted to the type of the variable. Assignment contexts allow the use of one of the following:

  • a widening primitive conversion (§5.1.2)
  • [...]

JLS 5.1.2 Widening Primitive Conversion

The following 19 specific conversions on primitive types are called the widening primitive conversions:

  • int to long, float, or double
  • [...]

Other data type suffix for literals

As mentioned above, there's also the D or d suffix for double. Consider this snippet for example:

static void f(int i) {
    System.out.println("(int)");
}
static void f(double d) {
    System.out.println("(double)");
}

//...
f(1);   // prints "(int)"
f(1D);  // prints "(double)"

There's also a suffix for long literals, which is L or l (lowercase letter). It is highly recommended that you use the uppercase variant.

JLS 3.10.1 Integer Literals

An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int. The suffix L is preferred, because the letter l (ell) is often hard to distinguish from the digit 1 (one).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...