• 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

 
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
can any one of u pls explain me how the casting takes place in the following code. Pls tell me how to find the output of the statements like..

class Test
{
public static void main(String args[])
{
byte b=(byte)150;
System.out.println(b);
}
}
Output: -106

Thanx in advance
 
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
byte = 8 bits => 2^8

-106 == 150 mod 256

Windening conversion to char, calling public void println(char x)

See:

class Test
{
public static void main(String args[])
{
byte b=(byte)150;
byte c=(byte)-106;
System.out.println(b);
System.out.println(b==c);
}
}
 
Naresh Gunda
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanq Renato Losio
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There is really no modulo stuff going on in casting.

150 = 128 + 16 + 4 + 2 = 0000 0000 0000 0000 0000 0000 1001 0110
Casting to a byte just takes the last (rightmost 8 bits) to get 1001 0110.

This is a negative number because of the highorder bit being set, so let's take the ones complement and add 1.

~1001 0110 is 0110 1001. Adding one, we get 0110 1010. This is 64 + 32 + 8 + 2 = 106.

So 150 (an int literal) cast to a byte gives -106.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic