• 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
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Devaka Cooray
  • Ron McLeod
  • paul wheaton
Saloon Keepers:
  • Tim Moores
  • Piet Souris
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Frits Walraven
  • Scott Selikoff

Explicit Type Casting

 
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

I have a doubt in explicit typecasting .How internally it happens can any body explain briefly (In case of Byte or int)how -128 has come in the output


public class test{
public static void main(String[] args)
{
byte d=(byte)128;
System.out.println(d);
}
}
o/p -128
 
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Its simple.
Size of byte is 8 bits, So the range of values it can take
is -2x7 to + 2x7-1 which is (-128 to 127) . If you assign any value out of this range it will cycle through the above range [bit calculation]. Since you have assigned 128 which is excatly next number to 127 and so the value thats stored in byte variable is -128.
Hope this answers your question.
Thanks
Deepak
 
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Refer pag 186 K&B Ch-3 Indian Sub-Continent Edition
 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey it's simple

128 in bits is 1000 0000

A byte has it's 8th bit as the sign bit.
Hence 1000 0000 , a byte will interpret as negative number and
the no. will be calculated using 2's complement.

Which means 1000 0000 --> 0111 1111
+ 1
----------
1000 0000

O/P -128
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi
Amit M

The Java Ranch follows a policy regarding user names.
See here:
http://www.javaranch.com/name.jsp


So, would you please change your user name before your next posting?
It will not affect anything you've already posted here. Just your user name will update.

Regards,
Bu.
 
You can't have everything. Where would you put it?
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic