This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Qs about literals Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Qs about literals" Watch "Qs about literals" New topic
Author

Qs about literals

Paulo Aquino
Ranch Hand

Joined: Apr 29, 2002
Posts: 200


Why is it that float f = 1/3 doesn't generate a compile time error while float d = .3333 gives a "possible loss of precision" compile time error? I know for a fact that numbers with decimal places are double by default , but 1/3 = .333 right? I'm just confused. Thanks.


Be Afraid...Be very Afraid...
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Surprise yourself



Tony Morris
Java Q&A (FAQ, Trivia)
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
I know for a fact that numbers with decimal places are double by default

And you should also know that a double cannot be assigned to a float without a cast.
"float d = .3333f;" works fine.
"float d = (float).3333;" works as well.

Don't forget to run the code in Tony's post and explain the result.


Mike Gershman
SCJP 1.4, SCWCD in process
Paulo Aquino
Ranch Hand

Joined: Apr 29, 2002
Posts: 200
Oh I forgot to print out the results. I had no idea that the result will be different. Anyway, thanks for the heads up!
Rahul Bhosale
Ranch Hand

Joined: Mar 10, 2005
Posts: 77
Is it because at run time 1/3 is treated as int division resulting in zero and when assigned to a float, it prints 0.0?



RB
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Qs about literals