-2

Is declaring a variable using float as final not allowed in java?

(using JDK 1.8.0.201, by the way)

final float TESTVARIABLE = .5;

expected: float should be allowed, as I only need a memory space sized for a float

Error:

Required: float
Found:    double

Actual:

final double TESTVARIABLE = .5;

the double variable type works, but the float variable type does not.

EDIT: this is asking about the error, and why the error is popping up.

this is also asking whether the float could be declared as final.

(this is just for those who are just starting java, and don't know how to fix errors that their CS teachers don't know how to fix.)

(yes, i know that's repetitive, but that was the best way that I could think of >to explain it.)

can you guys make a java-errors tag, so that this post could be more easily found?

Community
  • 1
  • 1

1 Answers1

2

It has nothing to do with final. When you type .5, it is a double literal, but you're attempting to assign it to a float. That is what causes the error.

float TESTVARIABLE = .5;  // error even without final

Place a f or F suffix on the numeric literal to make it a float literal, decimal point or not.

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.

final float TESTVARIABLE = .5f;
rgettman
  • 176,041
  • 30
  • 275
  • 357