• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Java data types: conversion

 
Ranch Hand
Posts: 234
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi guys, this question on Glenn, Mitchell. OCAJP Oracle Certified Associate Java SE 8 Programmer Practice Exams (Kindle Locations 19486-19488). Enthuware. Kindle Edition.

Consider the following code:

What will it print when run? Select 1 option
A. It will print 0.
B. It will not print 0.
C. It will not compile.
D. It will throw an exception at runtime.
E. None of the above.


I got this wrong and saiid it prints 0, but it in fact prints -46. Now how am I supposed to know that without compiling it and run it? Is there a general rule I can get out of this? The explanation says

the information was lost during the conversion from type int to type float as values of type float are not precise to nine significant digits.


Is that the case for only numbers with 9 digits?

 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jason Attin wrote: The explanation says

the information was lost during the conversion from type int to type float as values of type float are not precise to nine significant digits.


Is that the case for only numbers with 9 digits?



I would really be careful with this -- as it is more like "around 9 digits".

First, notice that phrase "significant". So, how many significant digits does "12340000000" have?

Second, while you understand 9 digits in scientific notation, the computer doesn't store it that way. Floating point is stored as a binary number that will be multiplied by 2 to the power of another binary number. And there may be lots of precision loss during the conversion of a decimal number that will be multiplied by 10 to the power of another decimal number. Add to that, normalization, blah, blah, blah ...

It is more like "around 9 significant digits". It's a rough estimate. So, don't depend on it.

Henry
reply
    Bookmark Topic Watch Topic
  • New Topic