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

# Mock question from Jaworski

Ranch Hand
Posts: 35
• Number of slices to send:
Optional 'thank-you' note:
Hi, Can anybody explain the output of the following code?
public class Test{
double d1=1.0;
double d2=0.0;
d1=d1/d2;
byte b = (byte)d1;
public static void main (String[] args){
System.out.println("b value is" + b);
}}
the given answer is -1. the mysterious part of this code is the casting d1 to b (which is of type byte). But at this moment d1 is infinity. How can this be done?

Ranch Hand
Posts: 103
• Number of slices to send:
Optional 'thank-you' note:
Good, you asked this question. I was baffled by this too!
The only guess I have is that all bits are set to 1 for infinity and when you cast a double to a byte the LSB(least significant byte) is assigned. Since this is still all 1s, the byte value turns out to be -1.
Savithri

Ranch Hand
Posts: 146
• Number of slices to send:
Optional 'thank-you' note:
Hi,
Did you actaully check the output on your machine??
Regards,
Milind

Savithri Devaraj
Ranch Hand
Posts: 103
• Number of slices to send:
Optional 'thank-you' note:
Yes I did! The strange thing here is, if you cast it to an integer variable, the int variable gets a large value of 2147483647.
Savithri

Author and all-around good cowpoke
Posts: 13078
6
• Number of slices to send:
Optional 'thank-you' note:
As I recall, division by zero in floating point give you postive or negative infinity - special constants defined in the Float and Double classes. Float.POSITIVE_INFINITY and .NEGATIVE_INFINITY
The other special constants are MAX_VALUE, MIN_VALUE and NaN (Not A Number)
I didn't realize you could cast those constants to int - pretty neat.

 Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters?