Java Reference
In-Depth Information
• Long integer to byte integer, short integer, character, or integer
• Floating-point to byte integer, short integer, character, integer, or long integer
• Doubleprecisionfloating-pointtobyteinteger,shortinteger,character,integer,
long integer, or floating-point
Acastoperatorisnotalwaysrequiredwhenconvertingfrommoretofewerbits,and
where no data loss occurs. For example, when it encounters
byte b = 100;
, the
compilergeneratescodethatassignsinteger100tobyteintegervariable
b
because100
can easily fit into the 8-bit storage location assigned to this variable.
Conditional Operators
The conditional operators consist of conditional AND (
&&
), conditional OR (
||
), and
conditional(
?:
).Thefirsttwooperatorsalwaysevaluatetheirleftoperand(aBoolean
expressionthatevaluatestotrueorfalse)andconditionallyevaluatetheirrightoperand
(another Boolean expression). The third operator evaluates one of two operands based
upon a third Boolean operand.
Conditional AND always evaluates its left operand and evaluates its right operand
only when its left operand evaluates to true. For example,
age > 64 &&
stillWorking
first evaluates
age > 64
. If this subexpression is true,
stillWorking
is evaluated, and its true or false value (
stillWorking
is a
Booleanvariable)servesasthevalueoftheoverallexpression.If
age > 64
isfalse,
stillWorking
is not evaluated.
ConditionalORalwaysevaluatesitsleftoperandandevaluatesitsrightoperandonly
whenitsleftoperandevaluatestofalse.Forexample,
value < 20 || value >
40
firstevaluates
value < 20
.Ifthissubexpressionisfalse,
value > 40
iseval-
uated,anditstrueorfalsevalueservesastheoverallexpression'svalue.If
value <
20
is true,
value > 40
is not evaluated.
ConditionalANDandconditionalORboostperformancebypreventingtheunneces-
saryevaluationofsubexpressions,whichisknownas
short-circuiting
.Forexample,if
itsleftoperandisfalse,thereisnowaythatconditionalAND'srightoperandcanchange
the fact that the overall expression will evaluate to false.
If you aren't careful, short-circuiting can prevent
side effects
(the results of subex-
pressionsthatpersistafterthesubexpressionshavebeenevaluated)fromexecuting.For
example,
age > 64 && ++numEmployees > 5
increments
numEmployees
for
only those employees whose ages are greater than 64. Incrementing
numEmployees
is an example of a side effect because the value in
numEmployees
persists after the
subexpression
++numEmployees > 5
has evaluated.