A single-line loop with a mandatory pair of braces in Java

Viewed 5439

The code in the following snippet works just fine. It counts the number of objects created using a static field of type int which is cnt.

public class Main
{
    private static int cnt;

    public Main()
    {
        ++cnt;
    }

    public static void main(String[] args)
    {
        for (int a=0;a<10;a++)
        {
            Main main=new Main();
        }

        /*for (int a=0;a<10;a++)
            Main main=new Main();*/

        System.out.println("Number of objects created : "+cnt+"\n\n");
    }
}

It displays the following output.

Number of objects created : 10

The only question is that when I remove the pair of curly braces from the above for loop (see the commented for loop), a compile-time error is issued indicating

not a statement.

Why in this particular situation, a pair of braces is mandatory even though the loop contains only a single statement?

3 Answers
Related