wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Mock question from Jaworski Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Mock question from Jaworski" Watch "Mock question from Jaworski" New topic
Author

Mock question from Jaworski

Jason
Ranch Hand

Joined: Dec 06, 2000
Posts: 35
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

Joined: Jun 26, 2000
Posts: 103
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

Joined: Jun 01, 2000
Posts: 146
Hi,
Did you actaully check the output on your machine??
Regards,
Milind
Savithri Devaraj
Ranch Hand

Joined: Jun 26, 2000
Posts: 103
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

Joined: Mar 22, 2000
Posts: 12761
    
    5
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.
 
wood burning stoves
 
subject: Mock question from Jaworski
 
Similar Threads
Issue adding double value
Mock Question
Casting Related Doubt
why the code is giving the answer as -1
narrowing double to byte question.