Forums Register Login

Constants and Default Values

+Pie Number of slices to send: Send
I'm learning Java using Introduction to Programming with Java: A Problem Solving approach. The discussion of constants has me a little confused.
The statement is made that "The default type for floating-point constants is double. Then they show the following example:

float gpa = 2.30;
float mpg;
mpg = 28.6;

They indicate that 2.30 and 28.6 default to double data type.

BUT they've told gpa to be a float. They further indicate that if you REALLY want gpa to be a float then declare it as:
float gpa = 2.30f;

But havent't I already told gpa to be a float when I use float gpa = 2.30. Why do I have to tell it "twice" by using f after my value? Obviously, I'm missing something in my understanding.
+Pie Number of slices to send: Send
The default type for floating point literals is double, as mandated by the language specification: http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.2

If the book uses the word 'constants' for 'literals' I can see how that could be confusing.

And welcome to the Ranch!
+Pie Number of slices to send: Send
 

Marie Kolanda wrote:BUT they've told gpa to be a float. They further indicate that if you REALLY want gpa to be a float then declare it as:
float gpa = 2.30f;


<nitpick>
That's actually not quite right. You already defined gpa to be a float by
float gpa = ...

it's the literal that isn't a float. In general, it doesn't make much difference since doubles can usually be converted to floats.

Try
float gpa = 1E100;
though.

</nitpick>

Winston
+Pie Number of slices to send: Send
http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.2

Thanks for the links. Think I'm getting it now.
Let's get him boys! We'll make him read this tiny ad!
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 716 times.
Similar Threads
help with methods return types
Assignment to float
Automatic type promotion
Please Help!
Primitive data types - example for usage, please?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 05:00:46.