aspose file tools*
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Explicit cast" Watch "Explicit cast" New topic
Author

Explicit cast

Sangita Mishra
Greenhorn

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 :-

10000010
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
Greenhorn

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 number.so take the 2's complement for the number 130

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

01111110 is -126

hope you understand


regards
Dinesh
Sangita Mishra
Greenhorn

Joined: Jun 15, 2005
Posts: 22
Yes, it's very much clear now.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Explicit cast
 
Similar Threads
casting shifted values
casting question
Primitive Casting
casting
Primitive casting