File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Mock question from Jaworski" Watch "Mock question from Jaworski" New topic

Mock question from Jaworski

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;
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.
Milind Kulkarni
Ranch Hand

Joined: Jun 01, 2000
Posts: 146
Did you actaully check the output on your machine??
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.
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13037
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.
I agree. Here's the link:
subject: Mock question from Jaworski
It's not a secret anymore!