0

Hi there, I am just beginning to learn java right now, and have a real begeinner question. I ahve read that when you declare a float variable and ssigna value to it the number has to be followed by an "f". What I coudln't find out is why:
var floatNumber = 12.5f;
What happened if I omit the "f" at the end?
thanks

3
Contributors
13
Replies
14
Views
5 Years
Discussion Span
Last Post by Violet_82
0

That doesn't look like valid java code. var is not part of java.

What happened if I omit the "f" at the end?

If it is java, compile and execute the program and see what happens.

0

"var" isn't Java, but anyway, in Java if you omit the "f", eg 12.5, it's assumed to be a double (same as float but twice as many bits for much greater accuracy).

0

apology, didn't meant o iclude "var" I meant justfloatNumber = 12.5f;

if you omit the "f", eg 12.5, it's assumed to be a double

thanks for clarifying this, so the float type declaration is always invariably
float varName = numberf;?
thanks

0

Yes, because if you code

float ff = 12.5;

the 12.5 will be a double constant, and Java will not automatically convert a double to a float becuase that looses precision. You will get an error "Type mismatch: cannot convert from double to float"

(ps: You can also use float ff = 1; because Java will automatically convert an int to float)

0

I see, I think I neeed to know a bit more about this, like double constants etc. ANy suggestion where I can do that please?
thanks

0

thanks I had a quick read but can't find anything about constant...what's a "double constant"?

0

Look at the Floating-Point Literals section.
I think a literal is what you are calling a constant.

Edited by NormR1

0

In the Lava Language Spec - the definitive description of the Java Language - the words constant and literal are used for two related but different meanings:
a "constant" is a field whose value cannot be changed
a "literal" is a value; it has no name, it just is what it is.
So in the code
final double PI = 3.14159;
PI is a constant, and 3.14159 is a literal.

0

ok I think I understand that but

Yes, because if you code

float ff = 12.5;
the 12.5 will be a double constant,

So why is 12.5 a constant here? Shouldn't it be a literal?

0

Oh dear! You caught me out there! I was being sloppy with my terminology and yes, I should have said literal. (In my defense we were discussing float vs double there, it was only later that we got onto constant vs literal.)
You're right. My fault. :)
J

0

Not a problem at all : - )! It's that I was getting really confused, thanks for clarifying

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.