aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Primitive casting 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 "Primitive casting" Watch "Primitive casting" New topic
Author

Primitive casting

sonia jaswal
Ranch Hand

Joined: Jun 01, 2007
Posts: 42
how do we cast from long to byte?
Venkat Kanneganti
Ranch Hand

Joined: Nov 30, 2007
Posts: 43
Hi,
USe explicit casting
like
long l=120;
byte b=(byte)l;
Peter Ricke
Greenhorn

Joined: Dec 07, 2007
Posts: 24
But be carefull:
casting a value in the correct range is doing what you will expect
e.g.:
long l = 10L;
byte b = (byte) l; //so b becomes 10

but:
long l = 130;
byte b = (byte) l;
here b does not become 130
because it can hold only values smaller than 128.

All leading bits will be removed (as long has 64bits and byte only 8)
This also influences the sign of the value, as the fist bit always represents this sign.
in this case b becomes -126.


========<br />class a{<br /> a a(a a){return (a)a;}<br />}
Venkat Kanneganti
Ranch Hand

Joined: Nov 30, 2007
Posts: 43
Hi Peter,
Thanks to your explanation.
i want to give an idea about casting but you have explained in dept
i think that may be useful to her
Peter Ricke
Greenhorn

Joined: Dec 07, 2007
Posts: 24
i was asked by private message to explain my example. maybe its interesting for someone else ...

2 things to know here
1)
every number tipe in java is signed,
so the first bit corresponds to the sign of that number:
0 is positive, 1 is negativ
2)
Explicit casting bigger types (eg an int to a byte) removes the leading bits.
e.g. you have a int (32 bit) 00000000 00000000 00000000 00000011 (3)
after casting to byte (8 bit) : 00000011 (still 3)

But if you habe a longer number (eg 130), you loose information:
00000000 00000000 00000000 10000010 (130)
becomes 10000010
here the leading sign is positive, but (ups)a positiv sign means a negative number!!! (see above)
To find out, how a negative number is calculated, you can look here
(but its not relevant for exam, i hope)
in short : substitute every bit with its complement
(here we get 01111101) and add 1
(we get 01111110) which corresponds to 126. As we know it is a negative number (see above) it has to be -126
but again: dont worry about for exam.
to play around, you can use e.g. Integer's parse()-Method with 2 parameters, first a binary String ("01111110") that a 2 (for binary)
You can print out the decimal number than...
regards
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Primitive casting