0
class things {
    public static void main(String args[]) {
        int [][] nothing;
        nothing = new int [4][5];
        int i,j,k = 0;

        for(i=0;i<4;i++)
            for(j=0;j<5;j++) {
                nothing[i][j] = k;
                k++;
            }

        // Display the 2-D array
        for(i=0;i<4;i++) {
            for(j=0;j<5;j++)
                System.out.print(nothing[i][j] + " ");
            System.out.println();
        }
    }
}

In the code given, { is in the second nested for loop of the first loop set but { is on the first line of loop the second loop set. So why and when to use {} in loops in Java. I mean I'm getting pretty different outputs when the {} are removed.

2 Answers2

1

if the for loop's body gonna contain one statement you don't actually need to put curly braces. If you omit the curly braces, then only the first Java statement will get executed, then automatically the 2nd line will be considered as the outer part of the loop.

for(int i = 0; i < 10; i++)
System.out.println("i is: " + i);  // executed inside  loop.
System.out.println("second line");   // executed after   loop.
Kabil
  • 79
  • 1
  • 8
  • 1
    This is correct. However I would recommend against using this feature- People are used to reading code a certain way, and its easy to misread code like this if you break from normal styles. It also makes it hard to edit the code- if you need to add a second line, you need to remember to add the curlies in (which is easy to gorget to do and will cost you time figuring it out). Its easier to just always use curly brackets and avoid problems. – Gabe Sechan May 23 '21 at 05:24
  • @GabeSechan Totally agree with that:). – Kabil May 23 '21 at 05:48
1

The if statement is specified as (simplified):

if ( Expression ) Statement
or
if ( Expression ) Statement else Statement

that is, by specification, no curly braces are needed but only one statement can be used in each branch (if and else). To use more than one statement in a branch, a block (inside curly braces) can be used.

It is recommended (IMO) to always use curly braces in the if statement, even if only one branch statement is needed. It is easier to maintain - no need to add the braces when adding additional statements; easier to read; helps prevent some errors like forgetting them when having code with wrong indentation like in:

if (foobar)
    System.out.print("foo");
    System.out.print("bar");    // this and next will always be executed,
    System.out.println();       // even if foobar is false

System.out.println("done);

Obs: there are some statements that require the curly braces, example the switch statement:

switch ( Expression ) { ... }

here they must be used (same for try statement or class declaration)