• 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
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Say4b: Typecasting

 
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If I have a long variable and I want to get an int value from it, I think I typecast it like this:
long argNum = Long.parseLong( whole );
int billNum = ( (int)argNum / 1000000000 );
But what happens if you cast argNum as an integer and argNum is larger than the largest number that Integer can handle? Will it still get cast?
 
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A cast will always work, but if the number is too big, it will get cut off. By casting something you are telling the compiler, I know that this is dangerous because I am going from a larger value down to a smaller value, but trust me, I know what I am doing.
For example if you have this:

The output will be -2
This has to do with the bit representation. The 32 bits for the int 254 will be cut down to 8 bits for a byte. The 24 high level bits will be lost, and what remains is the bit pattern for -2.
Bill
 
Hey! Wanna see my flashlight? It looks like this tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic