Java Reference
In-Depth Information
Theconditionaloperatorisusefulformakingadecisionbyevaluatingandreturning
one of two operands based upon the value of a third operand. The following example
converts a Boolean value to its integer equivalent (1 for true and 0 for false):
boolean b = true;
int i = b ? 1 : 0; // 1 assigns to i
Equality Operators
The equality operators consist of equality ( == ) and inequality ( != ). These operators
comparetheiroperandstodeterminewhethertheyareequalorunequal.Theformerop-
erator returns true when equal; the latter operator returns true when unequal. For ex-
ample,eachof 2 == 2 and 2 != 3 evaluatestotrue,whereaseachof 2 == 4 and
4 != 4 evaluates to false.
When it comes to object operands (discussed in Chapter 2 ), these operators do not
comparetheircontents.Forexample, "abc" == "xyz" doesnotcompare a with x .
Instead,becausestringliteralsarereally String objectsstoredinmemory( Chapter4
discusses this concept further), == compares the references to these objects.
Logical Operators
The logical operators consist of logical AND ( & ), logical complement ( ! ), logical ex-
clusive OR ( ^ ), and logical inclusive OR ( | ). Although these operators are similar
to their bitwise counterparts, whose operands must be integer/character, the operands
passed to the logical operators must be Boolean. For example, !false returns true.
Also,whenconfrontedwith age > 64 & stillWorking ,logicalANDevaluates
both subexpressions. This same pattern holds for logical exclusive OR and logical in-
clusive OR.
Member Access Operator
Thememberaccessoperator( . )isusedtoaccessaclass'smembersoranobject'smem-
bers. For example, String s = "Hello"; int len = s.length(); re-
turnsthelengthofthestringassignedtovariable s .Itdoessobycallingthe length()
method member of the String class. Chapter 2 discusses this topic in more detail.
Arraysarespecialobjectsthathaveasingle length member.Whenyouspecifyan
arrayvariablefollowedbythememberaccessoperator,followedby length ,theres-
ultingexpressionreturnsthenumberofelementsinthearrayasa32-bitinteger.Forex-
ample, ages.length returnsthelengthof(thenumberofelementsin)thearraythat
ages references.
Search WWH ::




Custom Search