站内搜索: 请输入搜索关键词
当前页面: 在线文档首页 > Java Tutorial 5.0 英文版

The if and else Statements - Java Tutorial 5.0 英文版

The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Language Basics

The if and else Statements

The if (in the glossary) statement enables your program to selectively execute other statements, based on some criteria. For example, suppose that your program prints debugging information, based on the value of a boolean variable named DEBUG. If DEBUG is true, the program prints debugging information, such as the value of a variable, say x. Otherwise, your program proceeds normally. A segment of code to implement this might look like this.
if (DEBUG) {
    System.out.println("DEBUG: x = " + x);
}
This is the simplest version of the if statement: The block governed by if is executed if a condition is true. Generally, the simple form of if can be written as follows.
if (expression) {
    statement(s)
}
What if you want to perform a different set of statements if the expression is false? You can use the else (in the glossary) statement for that. Consider another example: Suppose your program needs to perform different actions depending on whether the user clicks the OK button or another button in an alert window. The program could do this by using an if statement along with an else statement.
    . . .
    //Response is either OK or CANCEL, depending
    //on the button that the user pressed.
    . . .
if (response == OK) {
    //code to perform OK action
} else {
    //code to perform Cancel action
}
The else block is executed if the if part is false. Another form of the else statement, else if, executes a statement based on another expression. An if statement can have any number of companion else if statements but only one else. The following program, IfElseDemo (in a .java source file), assigns a grade based on the value of a test score: an A for a score of 90% or above, a B for a score of 80% or above, and so on.
public class IfElseDemo {
    public static void main(String[] args) {

        int testscore = 76;
        char grade;

        if (testscore >= 90) {
            grade = 'A';
        } else if (testscore >= 80) {
            grade = 'B';
        } else if (testscore >= 70) {
            grade = 'C';
        } else if (testscore >= 60) {
            grade = 'D';
        } else {
            grade = 'F';
        }
        System.out.println("Grade = " + grade);
    }
}
This is the output from the program.
Grade = C
You may have noticed that the value of testscore can satisfy more than one of the expressions in the compound if statement: 76 >= 70 and 76 >= 60. However, as the runtime system processes a compound if statement like this one, once a condition is satisfied, the appropriate statements are executed (grade = 'C';) and control passes out of the if statement without evaluating the remaining conditions.

The Java programming language supports an operator — ?: — that is a compact version of an if statement. Recall the following statement from the MaxVariablesDemo (in a .java source file) program.

if (Character.isUpperCase(aChar)) {
    System.out.println("The character " + aChar
                       + " is uppercase.");
} else {
    System.out.println("The character " + aChar
                       + " is lowercase.");
}
Here's how you could rewrite that statement using the ?: operator (shown in boldface).
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 a 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 easier to read.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.