Java Reference
In-Depth Information
You will find information on other methods in the class Character in the documentation for the class
that is part of the Java Development Kit.
The Conditional Operator
The conditional operator is sometimes called a ternary operator because it involves three operands. It is
best understood by looking at an example. Suppose we have two variables of type int , yourAge and
myAge , and we want to assign the greater of the values stored in yourAge and myAge to a third
variable also of type int , older . We can do this with the statement:
older = yourAge > myAge ? yourAge : myAge;
The conditional operator has a logical expression as its first argument, in this case yourAge>myAge . If
this expression is true , the operand which follows the ? symbol - in this case yourAge - is selected as
the value resulting from the operation. If the expression yourAge>myAge is false, the operand
which comes after the colon - in this case myAge - is selected as the value. Thus, the result of this
conditional expression is yourAge , if yourAge is greater than myAge , and myAge otherwise. This
value is then stored in the variable, older . The use of the conditional operator in this assignment
statement is equivalent to the if statement:
if(yourAge > myAge) {
older = yourAge;
} else {
older = myAge;
}
Remember, though, the conditional operator is an operator and not a statement, so it can be used in a
more complex expression involving other operators.
The conditional operator can be written generally as:
logical _ expression ? expression1 : expression2
If the logical _ expression evaluates as true , the result of the operation is the value of
expression1 , and if logical _ expression evaluates to false , the result is the value of
expression2 . Note that if expression1 is evaluated because logical _ expression is true , then
expression2 will not be, and vice versa.
There are lots of circumstances where the conditional operator can be used, and one common
application of it is to control output, depending on the result of an expression or the value of a variable.
You can vary a message by selecting one text string or another depending on the condition specified.
Try It Out - Conditional Plurals
Type in the following code which will add the correct ending to 'hat' depending on how many hats
you have:
public class ConditionalOp {
Search WWH ::




Custom Search