if 语句后面可以跟 else 语句,当 if 语句的布尔表达式值为 false 时,else 语句块会被执行。

if...else - 语法

if(Boolean_expression) {
   //当布尔表达式为true时执行
}else {
   //当布尔表达式为false时执行
}

if...else - 流程图

If Else Statement

if...else - 示例

public class Test {

   public static void main(String args[]) {
      int x=30;

      if( x < 20 ) {
         System.out.print("This is if statement");
      }else {
         System.out.print("This is else statement");
      }
   }
}

这将产生以下输出-

This is else statement

if ... else if ... else - 语句

if语句后可以跟可选的 else if ... else 语句,这对于使用单个if ... else if语句测试各种条件非常有用。

if(Boolean_expression 1) {
   //当布尔表达式 1 为true时执行
}else if(Boolean_expression 2) {
   //当布尔表达式 2 为true时执行
}else if(Boolean_expression 3) {
   //当布尔表达式 3 为true时执行
}else {
   //当上述条件均不成立时执行。
}

if ... else if ... else - 示例

public class Test {

   public static void main(String args[]) {
      int x=30;

      if( x == 10 ) {
         System.out.print("Value of X is 10");
      }else if( x == 20 ) {
         System.out.print("Value of X is 20");
      }else if( x == 30 ) {
         System.out.print("Value of X is 30");
      }else {
         System.out.print("This is else statement");
      }
   }
}

这将产生以下输出-

Value of X is 30

参考链接

https://www.learnfk.com/java/if-else-statement-in-java.html