Search code examples
javacurly-brackets

Usability of Curly Brackets


Say I have the following code below that only uses 2 curly brackets:

public void listFish(){
System.out.println(name + " with " + numFishCaught + " fish as follows: ");
for (Fish f: fishCaught)
    if (f != null)
    System.out.println(f.toString());}

Will it hurt my code or change the way it runs if I rewrite it this way? What is generally the correct way of using curly brackets? Thanks

public void listFish(){
System.out.println(name + " with " + numFishCaught + " fish as follows: ");
for (Fish f: fishCaught){
    if (f != null){
    System.out.println(f.toString());
    }
}     } 

Solution

  • 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

    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
         }
    }