• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Rob Spoor
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Scott Selikoff
Bartenders:
  • Piet Souris
  • Jj Roberts
  • fred rosenberger

5.0 == 5L

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello, I'm reading the rather splendid Java 2 Sun Certified Programmer & Developer. I'm doing OK - mostly, but I can't see why a float can be compared with a long i.e. 5.0 == 5L.

Maybe it is more accurate to say a double compared to a long as 5.0 would be a double if it was assigned to a variable. But you can also do the same with a byte and short etc.

Does 5.0 == 5L work because the compiler sees the double 5.0 and casts the long to a double? Then it is effectively testing the equality of two doubles?

I'm confused because java normally quite fussy, I mean java forces you to cast a float before accepting into a variable (you can't just say float x = 5.0) and you always get loss of precision compiler errors when implicitly casting downwards.

It must be that the bit representation of 5 (or 5L etc) and 5.0 are the same. But how can they be when one is a float?
 
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thats it!! You knew this one all along.
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Wyn Ackroyd:
...java forces you to cast a float before accepting into a variable (you can't just say float x = 5.0)...


That's because a numeric literal with a decimal point (for example, 5.0) is interpreted as type double, so assigning that value to a float variable is actually narrowing (and can lose "precision").

Note that Java is more flexible with literal int values, which can be assigned to byte or short variables without an explicit cast if the value fits within the range of the narrower type. (This is okay because precision is not an issue with integer types.)
[ July 11, 2005: Message edited by: marc weber ]
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic