DCFC21 DCFC21 - 1 month ago 4
Java Question

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

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 im new to java, I really dont know why that works.And I want to know if removing(or adding) the curly braces give any benefits/disadvantages?

Answer

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 curely 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)

Comments