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

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.

"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).

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

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)

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

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

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

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.

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?

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.