• 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
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Explicit cast

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 224
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, it's very much clear now.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic