aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes explain me (double) Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "explain me (double)" Watch "explain me (double)" New topic
Author

explain me (double)

Pankaja Shinde
Ranch Hand

Joined: Sep 15, 2006
Posts: 61
What happens when the following code gets executed:

class TechnoSample
{
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);
}
}

(1) It results in the throwing of an ArithmeticExcepiton
(2) It results in the throwing of a DivideByZeroException
(3) It displays the value 1.5
(4) It displays the value �1


Answer : -------------------------
4

Please explain me answer.

Pankaj Shinde
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

I think this is a special case that will probably not be on the exam.

The question is how to narrow a double value of Infinity (which results from double division by zero) to type byte. The process is described under JLS 5.1.3 Narrowing Primitive Conversions.

Basically, the double value is first converted to type int. Infinity is a special case in which the int's maximum value is used. In binary, this is 0111 1111 1111 1111 1111 1111 1111 1111. Next, the int is converted to a byte by discarding all but the 8 rightmost bits. This leaves 1111 1111, which is -1.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: explain me (double)
 
Similar Threads
Exception
why the code is giving the answer as -1
Floating-point Operations
Casting Related Doubt
A mock question