Is there a difference in removing the curly braces from If statements in java

For a single statement it will remain same, but if you want to group more than one statement in the if block then you have to use curly braces.

if("pie"== "pie"){
    System.out.println("Hurrah!");
    System.out.println("Hurrah!2");
}

if("pie"== "pie")
    System.out.println("Hurrah!"); //without braces only this statement will fall under if
    System.out.println("Hurrah!2"); //not this one

You should see: Blocks in Java

A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed. The following example, BlockDemo, illustrates the use of blocks:

class BlockDemo {
     public static void main(String[] args) {
          boolean condition = true;
          if (condition) { // begin block 1
               System.out.println("Condition is true.");
          } // end block one
          else { // begin block 2
               System.out.println("Condition is false.");
          } // end block 2
     }
}

(example from the above link)


No, there is absolutely no difference: a pair of curly braces makes multiple statements into a single one; if, while, for, and so on expect a single statement; if you need to guard only one statement, you do not need braces.

However, many software shops insist on having braces even for a single statement. The reason is errors like this:

if (x > 20)
    x -= 7;
    y -= 8;

The statements above are misleading: the indentation leads you to believe that both assignments are protected, while in reality only the first one is. The reason for that is that whitespace in Java is insignificant: indenting a statement does not change its placement in the overall flow of the program. Errors like the above are very hard to find, so adopting a rule to prevent them in the first place is a good idea.


As @rajesh says, braces are optional when the body is a single statement.

Having said that, leaving the braces in even for single statement cases is recommended by some coding styles because you (or the programmer who comes after you) are less likely to make errors when you change the code later.

if("pie"== "pie")
    System.out.println("Hurrah!");
    System.out.println("Tricked you");

The second print, Tricked you, is not actually in the if, it just looks like it because of the indentation.

However that is only a style point, not universally accepted, and certainly a competent programmer needs to be able to read both forms.