• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

casting problem

 
Ranch Hand
Posts: 396
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanx vasan,
it cleared my doubt.
deekasha
[This message has been edited by deekasha gunwant (edited August 01, 2000).]
 
Your mother was a hamster and your father was a tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic