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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With