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