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?
When you declare a variable (
mainin this case):it doesn’t count as a statement, even if it has side-effects. For it to be a proper statement, you should just do
So why is
allowed?
{ ... }is a block of code, and does count as a statement. In this case themainvariable 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.