File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Explicit cast Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Explicit cast" Watch "Explicit cast" New topic

Explicit cast

Sangita Mishra

Joined: Jun 15, 2005
Posts: 22
How the answer is -126?

class Casting {
public static void main(String [] args) {
long l = 130L;
byte b = (byte)l;
System.out.println("The byte is " + b);

The code compiles fine, and when we run it we get the following:

%java Casting
The byte is -126
Mishra Anshu
Ranch Hand

Joined: Sep 16, 2003
Posts: 224
130L has its lower (rightmost )8 bits as :-

All the rest bits to the left are zeros.
When you narrow a primitive, Java simply truncates the higher-order bits that won't fit.

So, all the zeros to the left are get truncated and we rae left with
10000010 (which is a negative no. as the sign bit is 1).

Now what is it's value?
Get the 2's complement as follows :--

01111101 + 1 = 01111110 which is 126.
So, the result is -126.

"Ignorance is bliss"
C Dinesh Kumar

Joined: Jan 06, 2005
Posts: 4
long l = 130L;
byte b = (byte)l;

From the above statment you are assigning 130 to a byte b.but the byte can hold the value in between 127 to -128. so if you store value greater than 127 it will go to negative half for example if you store 128 means it will take as -128 and 129 means -127 and it will go like that.

Or else you can think in this way...

130 can be represented in binary form as 10000010. here the first bit(from left) indicates whether it is a positve or negative number.if it is set it indicates negative take the 2's complement for the number 130

1's complement==01111101
2's complement== 1(+)
(add 1 to -----------
1's complement) 01111110

01111110 is -126

hope you understand

Sangita Mishra

Joined: Jun 15, 2005
Posts: 22
Yes, it's very much clear now.
I agree. Here's the link:
subject: Explicit cast
It's not a secret anymore!