programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Constants and Default Values

Marie Kolanda
Greenhorn
Posts: 7
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.

Darryl Burke
Bartender
Posts: 5167
11
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!

Winston Gutkowski
Bartender
Posts: 10575
66
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

Marie Kolanda
Greenhorn
Posts: 7
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.