Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes casting problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "casting problem" Watch "casting problem" New topic
Author

casting problem

deekasha gunwant
Ranch Hand

Joined: May 06, 2000
Posts: 396
hi,
the following program gives -1 as o/p.
while i was thinking it will raise an exception commented line.
coz here after the division operation d1 has got 'infinity' as its value. so how we r putting infinity in a byte.

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; //// commented line
System.out.print(b);
}
}


regards
deekasha
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
when you cast a double to a byte, only the lower order bits are copied to the byte variable.
When a double has a postitive infinity, the lower order bits are 1111 1111.
When a double has a negative infinity, the lower order bits are 0000 0000.
So the following code will assign 1111 1111 to b. 1111 1111
is -1 in decimal.


double d1=1.0;
double d2=0.0;
double d3=d1/d2;
byte b=(byte)d3. // b = -1

The following code will assign 0000 0000 to b.
0000 0000 is 0 in decimal.


double d1= - 1.0;
double d2=0.0;
double d3=d1/d2;
byte b=(byte)d3. // b=0


deekasha gunwant
Ranch Hand

Joined: May 06, 2000
Posts: 396
thanx vasan,
it cleared my doubt.
deekasha
[This message has been edited by deekasha gunwant (edited August 01, 2000).]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: casting problem
 
Similar Threads
Mock Question
Casting Related Doubt
ques
1.0/0.0 -1.0/0.0 0.0/0.0
Mock question from Jaworski