M/F 2:30-3:20 |
CS 1130: Transition to OO Programming Spring 2016 |
Main
About: Overview Announcements Staff Consultants Calendar Materials: Texts DrJava Terminology Lectures: In-Class Web-Based VideoNote Assessment: Grading Assignments Labs Resources: CMS Piazza (link) Piazza (about) Java API Style Guide Academic Integrity |
The Conditional ExpressionThe purpose of the conditional expression is to select one of two expressions depending on a third, boolean, expression. The format for the conditional expression is
If the value of the <boolean-expression> is true, the value of the conditional expression is the value of <expression-1>; if it is false, the value of the conditional expression is the value of <expression-2>. An important point is that only one of <expression-1> and <expression-2> is evaluated when evaluating the conditional expression. For example, the divide-by-zero in the following expression causes no error because it is not evaluated:
Expressions <expression-1> and <expression-2> may be any expressions, as long as they have the same type (if one is wider than the other, the narrower one will automatically be promoted to the wider type). The conditional expression is known as a ternary operation, because it has three operands. Examples of UseYou can use a conditional expression anywhere you could use a more conventional expression. The following example uses the conditional expression to set c to the larger of a and b:
Be careful. The conditional operators Here's an example that creates a string that indicates
which is the larger of
Try writing a few conditional expressions in the interactions
pane in order to get familiar with them. For example, write an expression
that finds the smallest of three values Use the Conditional Expression with CareUsed indiscriminately, the conditional expression can be
hard to read. However, in some cases, its use can result in shorter and
simpler code. For example, consider setting a variable
In order to write this assignment without using the conditional
expression, you would need a sequence of statements and would probably
use at least two conditional statements |