Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Qs about literals

 
Paulo Aquino
Ranch Hand
Posts: 202
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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.
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Surprise yourself

 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Paulo Aquino
Ranch Hand
Posts: 202
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic