Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 840
Tiny Avatar asked Jul 22 '12 17:07

Tiny


People also ask

Do you need curly braces for for loop in Java?

You don't actually need the curly braces around the for loop body. If you omit the curly braces, then only the first Java statement after the for loop statement is executed. Here is an example: for(int i = 0; i < 10; i++) System.

What are the three types of loops available in Java?

In Java, there are three kinds of loops which are – the for loop, the while loop, and the do-while loop. All these three loop constructs of Java executes a set of repeated statements as long as a specified condition remains true. This particular condition is generally known as loop control.

What are the parts of a for loop in Java?

Similar to a While loop, a For loop consists of three parts: the keyword For that starts the loop, the condition being tested, and the EndFor keyword that terminates the loop.


1 Answers

When you declare a variable (main in this case):

Main main = new Main(); 

it doesn't count as a statement, even if it has side-effects. For it to be a proper statement, you should just do

new Main(); 

So why is

... {     Main main = new Main(); } 

allowed? { ... } is a block of code, and does count as a statement. In this case the main variable could be used after the declaration, but before the closing brace. Some compilers ignore the fact that it's indeed not used, other compilers emit warnings regarding this.

like image 191
aioobe Avatar answered Sep 21 '22 03:09

aioobe