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

user735977 picture user735977 · Apr 3, 2013 · Viewed 45.9k times · Source

While watching thenewbostons tutorial on basic java, he teaches us to do if statements like this.(Notice the curly Braces)

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

So I tried removing the curly braces

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

And it still works! Since I'm new to java, I don't know why that works. And I want to know if removing(or adding) the curly braces give any benefits/disadvantages.

Answer

Habib picture Habib · Apr 3, 2013

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)