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

前端 未结 4 1360
遇见更好的自我
遇见更好的自我 2020-12-11 01:03

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

4条回答
  •  生来不讨喜
    2020-12-11 01:13

    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.

提交回复
热议问题