Java-if-else-statement-in-java

提供:Dev Guides
移動先:案内検索

Javaのif-elseステートメント

*if* ステートメントの後にオプションの *else* ステートメントを続けることができます。これは、ブール式がfalseの場合に実行されます。

構文

以下は、if …​ elseステートメントの構文です-

if(Boolean_expression) {
  //Executes when the Boolean expression is true
}else {
  //Executes when the Boolean expression is false
}

ブール式の評価がtrueの場合、コードのifブロックが実行され、そうでない場合はコードのブロックが実行されます。

流れ図

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、else if、elseステートメントを使用する場合、留意すべき点がいくつかあります。

  • ifには0個または1個のelseを含めることができ、else ifの後に来る必要があります。
  • ifは、0個以上の他のifを持つことができ、elseの前に来る必要があります。
  • else ifが成功すると、残りのelse ifまたはelseはテストされません。

構文

以下は、if …​ elseステートメントの構文です-

if(Boolean_expression 1) {
  //Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2) {
  //Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3) {
  //Executes when the Boolean expression 3 is true
}else {
  //Executes when the none of the above condition is true.
}

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