• Post Reply Bookmark Topic Watch Topic
  • New Topic

Constants and Default Values  RSS feed

 
Marie Kolanda
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!