Java if 语句由一个布尔表达式后跟一个或多个语句组成。

语法

以下是 if 语句的语法 

if(Boolean_expression) {
   // 如果布尔表达式为 true 则执行语句
} 

如果布尔表达式的计算结果为 true,则将执行 if 语句内的代码块。如果没有,则执行 if 语句结束后(右花括号后)的第一组代码。

流程图

Java if 语句

示例 1

在此示例中,我们将展示如何使用 if 语句来检查变量 x 的值是否小于 20 . 由于 x 小于 20,因此将打印 if 块中的语句。

public class Test {

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

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

输出

This is if statement. 

示例 2

在此示例中,我们显示如何使用 if 语句来检查布尔值是 true 还是 false。由于 x 小于 20,结果将为 true,并且将打印 if 块中的语句。

public class Test {

   public static void main(String args[]) {
      int x = 10;
      boolean result = x < 20;

      if( result ) {
         System.out.print("This is if statement");
      }
   }
} 

输出

This is if statement. 

示例 3

在此示例中,我们展示了如何使用 if 语句来检查布尔值是否为 false。由于 x 不大于 20,结果将为 true,并且将打印 if 块中的语句。

public class Test {

   public static void main(String args[]) {
      int x = 10;
      boolean result = x > 20;

      if( !result ) {
         System.out.print("This is if statement");
      }
   }
} 

输出

This is if statement.