Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Mock question from Jaworski

 
Jason
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Savithri Devaraj
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Milind Kulkarni
Ranch Hand
Posts: 146
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Did you actaully check the output on your machine??
Regards,
Milind
 
Savithri Devaraj
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13074
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic