user19254373
user19254373

Reputation:

Should we add "d", "f", etc. at the end of double, float values in Java?

I am generally confused when defining double and float variables and as far as I know, it is good practice to add "d", "f", etc. at the end of double, float values. However, as the IDE does not warn me, generally I omit them and think it would also be ok and no need to add these letters. Regarding to these variables:

1. Is there any letter except from "d" and "f" added to the variable definitions (double, float) in Java?

2. Why do we add these letters at the end of float and double variable definitions? And should we use or not?

3. When defining these variables (except from List, Map, etc.) as shown below, should I prefer primitive or wrapper class version of them?

I simply define a double like:

double quantityAmount = 200d;

// or

double quantityAmount = 200;

Could you please clarify me about this issue?

Upvotes: 0

Views: 1519

Answers (2)

DarkFlame
DarkFlame

Reputation: 16

  1. for float(F or f) and double(D or d) for more check (Default Values):https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html. The floating point types (float and double) can also be expressed using E or e (for scientific notation), F or f (32-bit float literal) and D or d (64-bit double literal; this is the default and by convention is omitted).
  2. A floating-point literal is of type float if it ends with the letter F or f; otherwise its type is double and it can optionally end with the letter D or d.
  3. that depends on you. :)

Upvotes: 0

Marcus Müller
Marcus Müller

Reputation: 36346

  1. yes. Read the official language documentation for a full list! https://docs.oracle.com/javase/specs/jls/se11/html/jls-3.html#jls-3.10
  2. Why: to denote the type when you need to specify the type; for example, say you have an overloaded function that has one implementation for int, and one for double; if you pass 300, it will call the int version, if you pass 300d, it will call the double version.
  3. Preference is a personal thing, I can't tell you what you like. Functionally, both are constant initializations with a trivial data type and do (bytecode-bitwise!) exactly the same.

Upvotes: 1

Related Questions