- Home
- Objectives

- XyzWs Study Guides
- Study Guides
- Study Notes
- Resources

- Mock Exams
SCJP Study Guide:
Flow Control
Printer-friendly version |
Mail this to a friend
The 'if' Statement
Purpose
The if statement enables your program to make decisions, and execute different parts of your program depending on a boolean true/false value.
Syntax
The if statement has this form:
if ( booleanexpression) {
statment(s);
}
or
if ( booleanexpression) {
statement(s);
} else {
statement(s);
}
The Java programming language supports an operator, ?:, that is a compact version of an if statement. For example:
if (Character.isUpperCase(aChar)) {
System.out.println("The character " + aChar + " is upper case.");
} else {
System.out.println("The character " + aChar + " is lower case.");
}
We could rewrite that statement using the ?: operator:
System.out.println("The character " + aChar + " is " +
(Character.isUpperCase(aChar) ? "upper" : "lower") +
"case.");
The ?: operator returns the string "upper" if the isUpperCase method returns true. Otherwise, it returns the string "lower". The result is concatenated with other parts of the message to be displayed. Using ?: makes sense here because the if statement is secondary to the call to the println method. Once you get used to this construct, it also makes the code more concise.
Notes
The expression is called the condition of if statement. The expression must evaluates to a boolean type (true/false).
The block of statements governed by if is excuted if the condition with the "if" keyword evaluate to true, otherwise the block of statements governed by else is excuted.
It is good programming style to always write the curly braces, {},
althought they are not needed if the clause contains only a single statement.
The curly braces are a general indicator in Java of a compound statement. This
is known as a block of code.
Another form of the else statement, else if, executes a statement based on another expression. This is a nest case for and only for a else block, i.e., the single statement in the else block is another if statement.
An if statement can have any number of companion else if statements but only one else. The else must come after any else if(s).
Once an else if succeeds, none of the remaining else if(s) or else will be test.
There are two reasons curly braces {} is good.
- Reliability. When code is modified, the indentation is such a strong indicator of structure that the programmer may not notice that the addition of a statement at the "correct" indentation level really isn't included in the scope of the if statement. This is a suprisingly common error.
- Readability. It is faster to read code with the braces because the reader doesn't have to keep in mind whether they are dealing with an un-braced single statement or a braced block.