Java Reference
In-Depth Information
0B00011010|0B10110111
results
in
00000000000000000000000010111111
The
&
,
^
, and
|
operators in the last three lines first convert their byte integer op-
erandsto32-bitintegervalues(through
sign bit extension
,copyingthesignbit'svalue
into the extra bits) before performing their operations.
Cast Operator
Thecastoperator—
(
type
)
—attemptstoconvertthetypeofitsoperandto
type
.This
operator exists because the compiler will not allow you to convert a value from one
type to another in which information will be lost without specifying your intention do
so(viathecastoperator).Forexample,whenpresentedwith
short s = 1.65+3;
,
thecompilerreportsanerrorbecauseattemptingtoconvertadoubleprecisionfloating-
pointvaluetoashortintegerresultsinthelossofthefraction
.65
—
s
wouldcontain4
instead of 4.65.
Recognizing thatinformationlossmightnotalwaysbeaproblem,Javapermitsyou
toexplicitlystateyourintentionbycastingtothetargettype.Forexample,
short s
= (short) 1.65+3;
tellsthecompilerthatyouwant
1.65+3
tobeconvertedtoa
short integer, and that you realize that the fraction will disappear.
Thefollowingexampleprovidesanotherdemonstrationoftheneedforacastoperat-
or:
char c = 'A';
byte b = c;
The compiler reports an error about loss of precision when it encounters
byte b
= c;
. The reason is that
c
can represent any unsigned integer value from 0 through
65535, whereas
b
can only represent a signed integer value from -128 through +127.
Eventhough
'A'
equatesto+65,whichcanfitwithin
b
'srange,
c
couldjusthaveeas-
ily been initialized to
'\u0323'
, which would not fit.
Thesolutiontothisproblemistointroducea
(byte)
cast,asfollows,whichcauses
the compiler to generate code to cast
c
's character type to byte integer:
byte b = (byte) c;
Java supports the following primitive type conversions via cast operators:
• Byte integer to character
• Short integer to byte integer or character
• Character to byte integer or short integer
• Integer to byte integer, short integer, or character