Java Reference
In-Depth Information
Conditional Operator ( ?: ) (Optional)
Certain if ... else statements can be written more concisely by using Java's conditional
operator. The conditional operator,writtenas ? : ,isaternary operator,whichmeans
that it takes three arguments. The syntax for using the conditional operator is:
expression1 ? expression2 : expression3
This type of statement is called a conditional expression. The conditional expression is
evaluated as follows: If expression1 evaluates to true , the result of the conditional
expression is expression2 ; otherwise, the result of the conditional expression is
expression3 . Note that expression1 is a logical expression.
Consider the following statements:
if (a >= b)
max = a;
else
max = b;
You can use the conditional operator to simplify the writing of this if ... else statement
as follows:
max = (a >= b) ? a : b;
Avoiding Bugs by Avoiding Partially Understood
Concepts and Techniques
The debugging sections in Chapters 2 and 3 illustrated how to understand and fix syntax
and logic errors. In this section, we will illustrate how to avoid bugs by avoiding partially
understood concepts and techniques.
The programs that you have written until now should have illustrated that a small error
such as omission of a semicolon at the end of a variable declaration or using a variable
without properly declaring it can prevent a program from successfully compiling. Simi-
larly, using a variable without properly initializing it can prevent a program from running
correctly. Recall that the condition associated with an if statement must be enclosed in
parentheses. Therefore, the following expression will result in a syntax error:
if score >= 90
Example 4-11 illustrates that an unintended semicolon following the condition of the
following if statement:
DEBUGGING
if (hours > 40.0);
can prevent successful compilation or correct execution.
The approach you take to solve a problem must use concepts and techniques correctly;
otherwise, your solution will be either incorrect or deficient. If you do not understand a
 
 
Search WWH ::




Custom Search