Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# casting problem

deekasha gunwant
Ranch Hand
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
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
Posts: 396
thanx vasan,
it cleared my doubt.
deekasha
[This message has been edited by deekasha gunwant (edited August 01, 2000).]