0

So in the videos I'm using to learn java they place a 'f' after float (per java rules), and he tells you to place a 'd' behind a decimal number and I want to know if its a good practice to do so?

int myIntValue = 5;
float myFloatValue = 5f;
double myDoubleValue = 5d ;
System.out.println("myIntValue = " + myIntValue);
System.out.println("myFloatValue = " + myFloatValue);
System.out.println("myDoubleValue = " + myDoubleValue);
Dillon Skaggs
  • 15
  • 1
  • 9

2 Answers2

1

d or D is not for "decimal" number, is for double. It's not necessary because every literal floating point number in Java is a double by default.

So, this:

double x = 5.0;

Will perform the same as this:

double x = 5d;

I want to know if its a good practice to do so

It's not a matter of good practice or not. Most code I've read omits the d at the end. If you feel more comfortable using the d for your literal values, then it's ok too.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
1

Yes, if you're not going to include the fractional part. 5 on its own is an integer literal, which is then promoted to double. 5d is a double literal. You can also write 5.0, which can't be an integer literal, and so is a floating-point literal.

From the second link above:

For decimal* floating-point literals, at least one digit (in either the whole number or the fraction part) and either a decimal point, an exponent, or a float** type suffix are required. All other parts are optional. The exponent, if present, is indicated by the ASCII letter e or E followed by an optionally signed integer.

(my emphasis)

Then later

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 (§4.2.3).


* Here they mean the number base (base 10), not a decimal type.

** Here they meant a floating point suffix, either f/F for float or d/D for double

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875