Using braces makes your 'if' statement clearer : If Statement « Statement Control « Java Tutorial






If there is only one statement in an if or else block, the braces are optional.

public class MainClass {

  public static void main(String[] args) {
    int a = 3;
    if (a > 3)
      a++;
    else
      a = 3;
  }

}

Consider the following example:

public class MainClass {

  public static void main(String[] args) {
    int a = 3, b = 1;

    if (a > 0 || b < 5)
      if (a > 2)
        System.out.println("a > 2");
      else
        System.out.println("a < 2");
  }

}
  1. It is hard to tell which if statement the else statement is associated with.
  2. Actually, An else statement is always associated with the immediately preceding if.

Using braces makes your code clearer.

public class MainClass {

  public static void main(String[] args) {
    int a = 3, b = 1;

    if (a > 0 || b < 5) {
      if (a > 2) {
        System.out.println("a > 2");
      } else {
        System.out.println("a < 2");
      }
    }
  }

}








4.2.If Statement
4.2.1.The if statement syntax
4.2.2.Expression indentation for if statement
4.2.3.Using braces makes your 'if' statement clearer
4.2.4.Multiple selections
4.2.5.The if Statement in action
4.2.6.The else Clause
4.2.7.Nested if Statements
4.2.8.Using && in if statement
4.2.9.Using || (or operator) in if statement