Java selection statement-general Linux technology-Linux programming and kernel information. The following is a detailed description. The programming language uses control statements to generate execution streams to change the program status, such as sequential execution and branch execution. Java program control statements are divided into the following types: selection, repetition, and redirection. Select a different execution path for your program based on the expression result or the Selection statement. Repeated (Iteration) statements enable the program to execute one or more statements repeatedly (that is, repeated statements form a loop ). The Jump statement allows your program to be executed in a non-linear manner. The following describes all the control statements in Java.
If you are familiar with C/C ++, it is easy to master Java Control statements. In fact, the control statements in Java are almost identical to those in C/C ++. Of course there are some differences between them-especially the break and continue statements.
Java supports the if statement and switch statement. These statements allow you to control the execution process of a program only when the program is running. If you do not have the C/C ++ programming background, you will be surprised by the powerful functions and flexibility of these two statements.
5.1.1 if statement
The if statement has been introduced in chapter 2nd. We will discuss it in detail here. The if statement is a condition branch statement in Java. It can divide the execution path of the program into two. The complete format of the if statement is as follows:
If (condition) statement1;
Else statement2;
Among them, if and else objects are a single statement (statement), or a program block. Condition can be any expression that returns a Boolean value. The else clause is optional.
The execution process of the if statement is as follows: if the condition is true, the if object (statement1) is executed; otherwise, the else object (statement2) is executed ). The two statements cannot be executed simultaneously at any time. Consider the following example:
Int a, B; //... if (a <B) a = 0; else B = 0;
In this example, if a is less than B, a is assigned 0; otherwise, B is assigned 0. In any case, a and B cannot be assigned 0 values.
Generally, expressions used to control if statements contain Relational operators. Of course, this is not technically necessary. You can use only one Boolean value to control the if statement, as shown in the following section:
Boolean dataAvailable;
//...
If (dataAvailable)
ProcessData ();
Else
WaitForMoreData ();
Remember, there can be only one sentence after an if or else statement. If you want to include more statements, you need to create a program block, as shown in the following example:
Int bytesAvailable;
//...
If (bytesAvailable> 0 ){
Here, if the variable bytesAvailable is greater than 0, all the statements in the if block will be executed.
Some Programmers think that it is very convenient to use the if statement followed by a braces, and even use braces when there is only one statement. This makes it easy to add other statements in the future, and you do not have to worry about forgetting brackets. In fact, failing to define a block is a common cause of errors. For example, consider the following program section:
Int bytesAvailable;
//...
If (bytesAvailable> 0 ){
ProcessData (); bytesAvailable-= n;
} Else
WaitForMoreData ();
BytesAvailable = n;
For orchestration reasons, it seems that the bytesAvailable = n statement should be executed in the else clause. However, when you call it, the blank is irrelevant to Java, and the compiler cannot know your intention. This program will be compiled, but errors will occur during application. The preceding example should be modified as follows:
Int bytesAvailable;
//...
If (bytesAvailable> 0 ){
ProcessData ();
BytesAvailable-= n;
} Else {
WaitForMoreData ();
BytesAvailable = n;
}
Nested if statement
The nested if statement is the object of another if or else statement. Nested if statements are often used in programming. When using nested if statements, you must remember that an else statement always corresponds to the nearest if statement in the same block as it, the if statement is not associated with other else statements. The following is an example:
If (I = 10) {if (j <20) a = B; if (k> 100) c = d; // this if iselse a = c; // associated with this else
}
Else a = d; // this else refers to if (I = 10)
As shown in the comment, the last else statement does not correspond to if (j <20) because they are not in the same block (although if (j <20) statement is not paired with the else latest if Statement ). The last else statement corresponds to if (I = 10 ). The internal else statement corresponds to if (k> 100) because it is the most recent if statement in the same block.
If-else-if step
The general programming structure based on nested if statements is called the if-else-if step. Its syntax is as follows:
If (condition) statement; else if (condition)
Statement;
.
.
.
Else
Statement;
The conditional expression is evaluated from top to bottom. Once a true condition is found, the statement associated with it is executed, and other parts of the step are ignored. If none of the conditions are true, execute the final else statement. The final else statement is often used as the default condition. If all other conditions fail to be tested, the final else statement is executed. If there is no final else statement and all other conditions fail, the program will not perform any action.
The following program uses the if-else-if step to determine the season of a month.
// Demonstrate if-else-if statements.
Class IfElse {
Public static void main (String args []) {
Int month = 4; // L
String season;
If (month = 12 | month = 1 | month = 2)
Season = "Winter ";
Else if (month = 3 | month = 4 | month = 5)
Season = "Spring ";
Else if (month = 6 | month = 7 | month = 8)
Season = "Summer ";
Else if (month = 9 | month = 10 | month = 11)
Season = "Autumn ";
Else
Season = "Bogus Month ";
System. out. println ("Your L is in the" + season + ".");
}
}
The program generates the following output:
Using L is in the Spring.
Before proceeding, you may want to test this program first. You will see that no matter what value you give month, there is only one statement in this step for execution.
5.1.2 switch statement
The switch statement is a multi-path branch Statement of Java. It provides a simple method to execute different parts of a program based on the value of an expression. Therefore, it provides a better choice than a series of if-else-if statements. The general format of the switch statement is as follows:
Switch (expression ){
Case value1:
// Statement sequence
Break;
Case value2:
// Statement sequence
Break;
.
.
.
Case valueN:
// Statement sequence
Break;
Default:
// Default statement sequence
}
Expression must be of the byte, short, int, or char type. The value after each case statement must be a specific constant compatible with the expression type (it must be a constant rather than a variable ). Duplicate case values are not allowed.
The execution process of the switch statement is as follows: The expression value is compared with the constant in each case statement. If a matching code is found, the code after the case statement is executed. If no case constant matches the expression value, the default statement is executed. Of course, the default statement is optional. If there is no matching case statement and no default statement, nothing will be executed.
The break statement in the case statement sequence causes the program stream to exit from the entire switch statement. When a break statement is run, the program starts to execute the first line of code after the entire switch statement. This has the effect of jumping out of the switch statement.
The following is a simple example of using the switch statement:
// A simple example of the switch.
Class SampleSwitch {
Public static void main (String args []) {
For (int I = 0; I <6; I ++)
Switch (I ){
Case 0:
System. out. println ("I is zero .");
Break;
Case 1:
System. out. println ("I is one .");
Break;
Case 2:
System. out. println ("I is two .");
Break;
Case 3:
System. out. println ("I is three .");
Break;
Default:
System. out. println ("I is greater than 3 .");
}
}
}
The output of this program is as follows:
I is zero.
I is one.
I is two.
I is three.
I is greater than 3.
I is greater than 3.
It can be seen that the related statement after the case constant that matches the I value is executed for each loop. Other statements are ignored. If I is greater than 3, no case statement can be matched. Therefore, the default statement is executed. The break statement is optional. If you omit the break statement, the program will continue to execute the next case statement. Sometimes there is no break between multiple case statements. For example, the following program:
// In a switch, break statements are optional.
Class MissingBreak {
Public static void main (String args []) {
For (int I = 0; I <12; I ++)
Switch (I ){
Case 0:
Case 1:
Case 2:
Case 3:
Case 4:
System. out. println ("I is less than 5 ");
Break;
Case 5:
Case 6:
Case 7:
Case 8:
Case 9:
System. out. println ("I is less than 10 ");
Break;
Default:
System. out. println ("I is 10 or more ");
}
}
}
The output of this program is as follows:
I is less than 5
I is less than 5
I is less than 5
I is less than 5
I is less than 5
I is less than 10
I is less than 10
I is less than 10
I is less than 10
I is less than 10
I is 10 or more
I is 10 or more
As demonstrated by this program, if there is no break statement, the program will continue to execute each of the following case statements
Statement until it encounters a break statement (or the end of the switch statement ). Of course, this example is constructed manually for the sake of examples. The omitted break statement has many practical applications in the real program.
. To demonstrate its more practical usage, let's consider the next example to rewrite the previous display season example. This overwrites
The switch statement is used to make program execution more efficient.
// An improved version of the season program.
Class Switch {
Public static void main (String args []) {
Int month = 4;
String season;
Switch (month ){
Case 12:
Case 1:
Case 2:
Season = "Winter ";
Break;
Case 3:
Case 4:
Case 5:
Season = "Spring ";
Break;
Case 6:
Case 7:
Case 8:
Season = "Summer ";
Break;
Case 9:
Case 10:
Case 11:
Season = "Autumn ";
Break;
Default:
Season = "Bogus Month";} System. out. println ("Your L is in the" + season + ".");
}
}
Nested switch statement
A switch statement can be used as a part of the sequence of statements of an external switch statement, which is called a nested switch statement. Because a switch statement defines its own block, the case constant of the external switch statement does not conflict with the internal switch statement. For example, the following program section is completely correct:
Switch (count ){
Case 1:
Switch (target) {// nested switch
Case 0:
System. out. println ("target is zero ");
Break;
Case 1: // no conflicts with outer switch
System. out. println ("target is one ");
Break ;}
Break;
Case 2 ://...
In this example, case 1 in an internal switch statement does not conflict with case 1 in an external switch statement. The variable count is only compared with the case statement of the outer layer. If the variable count is 1, the variable target is compared with the case statement in the inner layer.
To sum up, switch statements have three important features:
·
The switch statement is different from the if statement, where the switch statement can only test equal conditions, and the if statement can calculate any type of Boolean expression. That is, the switch statement can only find a value between the case constant and the value of the expression.
·
There are no two identical case constants in the same switch statement. Of course, the case constant in the external switch statement can be the same as the case constant in the internal switch statement.
·
The switch statement is generally more effective than a series of nested if statements.
The last point is particularly interesting, because it gives us an idea of how the Java compiler works. When a switch statement is compiled, the Java compiler checks each case constant and creates a "Jump table". This table is used to select the execution path based on the expression value. Therefore, if you need to select a group of values, the switch statement is much faster than the equivalent if-else statement. The compiler can do this because it knows that the case constant is of the same type. All you have to do is compare it with the switch expression to see if it is equal. The compiler does not have this function for a series of if expressions.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.