Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object creating statement in Java doesn't allow to use a single-line loop. Why?

Tags:

java

The following program has no importance of its own. It just counts the number of objects created through the use of a for loop using a static field inside the class Counter as shown below.

package temp;

final class Counter
{
    private static int cnt;

    public Counter()
    {
        cnt++;
    }

    public static int show()
    {
        return(cnt);
    }
}

final public class Main
{
    public static void main(String[] args)
    {
        for (int i=0;i<50;i++)
        {
            Counter counter=new Counter();
        }

        /*for (int i=0;i<50;i++)
            Counter counter=new Counter();*/

        System.out.print("\nNumber of objects constructed:->"+Counter.show()+"\n\n");
    }
}

The only question here is that the commented for loop means the same as the above for loop (the same thing is also applied to a while loop) doesn't work at all causing a compile-time error that indicates that "not a statement" means that in this particular situation, the pair of braces are mandatory even though the for loop contains only one statement! Why?

like image 905
Lion Avatar asked Nov 16 '11 01:11

Lion


People also ask

Can you create objects in a loop Java?

You CAN use a loop. The trick is that you have to save the reference to each one as you create it. A simple way would be to use an array. You have to declare the array outside the loop, then use your loop counter as the index into the array...

How do you create a new object in a for loop?

for(var x = 1; x<=10; x++){ var Object + x = new Object(); };

What are the three types of loops available in Java?

Java provides three types of Loops: for, while, and do-while. Four Elements control a loop: initialization expression(s), test expression, update expression, and loop-body.


2 Answers

To understand why this happens, you have to look at Java's Blocks and Statements syntax in the language specification.

A ForStatement is defined as:

ForStatement:
    for ( ForInitopt ; Expressionopt ; ForUpdateopt )
        Statement

Statement is defined as:

Statement:
    StatementWithoutTrailingSubstatement
    LabeledStatement
    IfThenStatement
    IfThenElseStatement
    WhileStatement
    ForStatement

StatementWithoutTrailingSubstatement:
    Block
    EmptyStatement
    ExpressionStatement
    SwitchStatement
    DoStatement
    BreakStatement
    ContinueStatement
    ReturnStatement
    SynchronizedStatement
    ThrowStatement
    TryStatement

Then, looking at Block:

Block:
    { BlockStatementsopt }

BlockStatements:
    BlockStatement
    BlockStatements BlockStatement

BlockStatement:
    LocalVariableDeclarationStatement
    ClassDeclaration
    Statement

You'll notice that, within this specification, LocalVariableDeclarationStatement is not valid unless it is in a block. But, because the ForStatement requires that it is followed by a statement, there MUST exist parenthesis in order to make the expression valid. As such, any local variable declaration would be invalid in the loop without the brackets.

like image 126
JasCav Avatar answered Sep 21 '22 15:09

JasCav


Because you're creating a scope variable. Java is telling you that this does nothing because all it does is allocate memory and as soon as the loop goes through again you lose that one and make a new one. Essentially the entire loop is a NOP which is why it's telling you that it reduces to a do nothing statement.

By the loop being a NOP I mean that the declaration in the loop is a NOP.

The reason the version with the braces work is because the compiler doesn't inspect the usage within the scope because there are braces. It's probably something to do with the parse tree generated from one line statements vs. the parse tree created when there's a full loop scope.

like image 43
Jesus Ramos Avatar answered Sep 21 '22 15:09

Jesus Ramos