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
• Number of slices to send:
Optional 'thank-you' note:
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
• Number of slices to send:
Optional 'thank-you' note:
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.
Thanks
Deepak

Ranch Hand
Posts: 169
• Number of slices to send:
Optional 'thank-you' note:
Refer pag 186 K&B Ch-3 Indian Sub-Continent Edition

Greenhorn
Posts: 15
• Number of slices to send:
Optional 'thank-you' note:
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
• Number of slices to send:
Optional 'thank-you' note:
Hi
Amit M

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