Java conditional statements if ... else
①if statement
An if statement contains a Boolean expression and one or multiple statements.
IF (Boolean expression) { // statement Boolean expression is true when it will be executed }
public class Test{ public static void main(String args[]){ int i=10; if(i<20){ System.out.println("if语句"); } } }
operation result
The if statement
②if ... else statement
end of the statement may be followed if else statement, if statement when the boolean expression is false time, else statement blocks are executed
IF (Boolean expressions) { // Boolean expression is true, when executed } ELAS { // boolean expression is false when the execution }
public class Test{ public static void main(String args[]){ int i=50; if(i<20){ System.out.println("if语句"); }else{ System.out.println("else语句"); } } }
operation result
else statement
③if ... else if ... else statement
if behind the statement may be followed by a lot else if ... else statement,
Note: if the statement at most one else statement, else statement following the else if all of the statements, if statements can have multiple else if statements; once one of the promising true Boolean expressions, and other statements skipped execution.
IF (Boolean expression 1 ) { // Boolean expression is true when performing 1 } the else IF (Boolean expression 2 ) { // Boolean expression is true when performing 2 } the else IF (Boolean expression 3 ) { // ...... } the else IF (Boolean expression. 4 ) { // ...... } the else IF (Boolean expression. 5 ) { // ...... } the else { // the above statement is not executed, this statement will be executed }
public class Test{ public static void main(String args[]){ int i=30; if(i==10){ System.out.println("i为10"); }else if(i==20){ System.out.println("i为20"); }else if(i==30){ System.out.println("i为30"); }else if(i==40){ System.out.println("i为40"); }the else { System.out.println ( "I do not know what" ); } } }
operation result
i 30
④ nested if ... else statement
fi (Boolean expression 1) { // Boolean expression is true when performing an IF (Boolean expression 2) { // boolean expression is true when performing 2 } }
public class Test{ public static void main(String args[]){ int i=10; int j=20; if(i<15){ System.out.println("i比15小"); if(j>15){ System.out.println("j比15大"); } } } }
operation result
i less than 15
big j than 15