Conditional branch statements can be subdivided into three forms according to their grammatical format.
if statement:
The if statement is a single-condition single-branch statement, which controls the flow of program execution based on a condition. The syntax format of the if statement is:
if(expression)/*If the expression is true, the compound statement will be executed, otherwise it will not be executed*/{//statement}
if-else statement:
The if-else statement is a single-condition double-branch statement, which controls the flow of program execution based on a condition. The syntax format of the if-else statement is:
if (expression)/*If the expression is true, execute statement 1, otherwise execute statement 2*/{//statement 1}else{//statement 2}
if-else if-else statement:
if-else The if-else statement is a multi-condition branch statement, that is, it controls the flow of program execution based on multiple conditions. The syntax format of the if-else if-else statement is:
if (expression 1)/*If expression 1 is true, execute statement 1, otherwise continue to judge expression 2*/{//Statement 1} elseif (expression 2)/*If expression 2 is true, execute statement 2, Otherwise, continue to judge expression 3*/{//Statement 2}elseif(expression 3)/*If expression 3 is true, execute statement 3, otherwise continue to judge the next expression*/{//Statement 3}......else /*If none of the above expressions are true, execute statement 4*/{//statement 4}
Notice:
1) The value of the expression in parentheses after the keyword if must be of type boolean.
2) In the if conditional branch statement, if there is only one statement in the compound statement, {} can be omitted.
Example:
publicclassMain{publicstaticvoidmain(Stringargs[]){intx=3;if(x==1){System.out.print(ValueofXis1);}elseif(x==2){System.out.print(ValueofXis2);}elseif (x==3){System.out.print(ValueofXis3);}else{System.out.print(ValueofXis0);}}}
The running results are as follows:
ValueofXis3