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)

Leave a Comment