This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

float error

 
Adam Vinueza
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm new to Java, and have been working my way through _Java in 21 days_, when I wrote this simple program to help myself understand casting better:
public class CastEx
{
public static void main(String[] arguments)
{
float k = 4.57;
k = (int)k;
System.out.println(k);
}
}
I got the following error message:
possible loss of precision
found: double
required: float,
followed by a little arrow pointing at the numeral 4.
This message seems to me to be telling me that I have somehow used a double type instead of a float, when float is specified in the program. What is happening here? I feel like I'm making some kind of basic, easy-to-fix error, but I don't see what I'm doing wrong.
 
Art Metzer
Ranch Hand
Posts: 241
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's OK, Adam, it's how we all learn.
Just as Java takes integral literals ( -8, 0, 14, +55, 1234567891011 ) to be ints, it takes decimal literals ( -2e10, -0.0, 5., 4.57 ) to be doubles. All you have to do to convince Java that 4.57 is a float and not a double is suffix it with f or F:

In the same way, if you want Java to consider an integral value to be a long, you have to suffix it with an l or an L. (The uppercase version is preferred, because the lowercase version can so easily be confused with the number 1.)
Hope this helps, Adam.
Art
 
Magesh Lakshmi
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
The reason is that when you try to store a float to an int, the precision would be lost.
So that if you try to store 5.7 ( which is a float ) to a int variable then it will store only 5.
 
Art Metzer
Ranch Hand
Posts: 241
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I also found this link for you, Adam, at the Java Language Specification:
http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#230798
Art
 
Adam Vinueza
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to Art and Magesh for your helpful comments. Of course the problem would turn out to have such a simple solution--would that all problems could be solved like that!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic