Win a copy of Design for the Mind this week in the Design forum!

# A mock question

yang ming
Greenhorn
Posts: 17
Hi,
Look at this mock question, can sb explain why the answer is "-1"?
/////////////////////////////////////////////
class Question {
public static void main(String[] args) {
double d1 = 1.0;
double d2 = 0.0;
byte b =1;
d1 = d1/d2;
b = (byte) d1;
System.out.print(b);
}
}
A It results in the throwing of an ArithmeticExcepiton.
B It results in the throwing of a DivedeByZeroException.
C It displays the value 1.5.
D It displays the value �1.
//////////////////////////////////////////////
Thanks

Dan Lajoy
Greenhorn
Posts: 19
I'm not sure but I think the answer is -1 because the division by 0 yields positive infinity. In binary conversion I believe that would be a 0 followed by 63 1's. Then when the double is cast to a byte, all the bits are chopped off except the last 8 - so you're left with 11111111. This is -1.
That's my take. Requesting confirmation from some seasoned pro's out there...

Yi Meng
Ranch Hand
Posts: 270
The process involved is that:
1. 1.0/0.0 results in Double.POSITIVE_INFINITY
2. Double.POSITIVE_INFINITY is converted to Integer.MAX_VALUE ('0' followed by 31 '1's)
3. Integer.MAX_VALUE is then cast to byte value, which simply takes the last 8 bits(11111111) and is -1.
try the following code
The output is:
Infinity
2147483647
-1

BTW, Double.POSITIVE_INFINITY is not a '0' followed by 61 '1's
quote from IEEE 754 standards:
The values +infinity and -infinity are denoted with an exponent of all 1s and a fraction of all 0s. The sign bit distinguishes between negative infinity and positive infinity. Being able to denote infinity as a specific value is useful because it allows operations to continue past overflow situations.

La Vish
Ranch Hand
Posts: 161
Or as the author,Jamie Jaworski,explains in his book,use the process of elimination.
double cannot throw exceptions given in A and B and byte cannot have values like 1.5 and so the correct answer has to be -1!
[ June 11, 2003: Message edited by: La Vish ]

Brian Joseph
Ranch Hand
Posts: 160
La Vish, that worked for me ;-), but you have to at least know or have seen that dividing by zero with a float/double works, and yeilds the special "positive/negative" infinity value.

La Vish
Ranch Hand
Posts: 161
Agreed,Brian.You are correct.
But learning java is one thing and passing SCJP is another. For some of the questions it is better to look at answers given and use the process of elimination.This saves time.
We also need to remember that passing SCJP does not make us experts in Java nor failing SCJP does not mean that we are not good at Java.