Error while declaring a variable inside for-loop along with print statement

user11564744 :

I was trying to learn how for-loop works, so I made such a code.

for(System.out.println("hi"),int i=0;i<5;System.out.println("yo"),i++) 
{
System.out.println("teapot");
}

This way I can understand, which part of for-loop is being executed when. But I am getting an error in the first line stating ".class expected". Maybe this simply means, I cannot declare a variable in the first line. So I reworked it, and now it works perfectly.

int i;
for(System.out.println("hi"),i=0;i<5;System.out.println("yo"),i++) 
{
System.out.println("teapot");
}

But I don't understand why I cannot declare a variable in the first line.

Andy Turner :

The syntax of a basic for loop is:

BasicForStatement:
  for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement

BasicForStatementNoShortIf:
  for ( [ForInit] ; [Expression] ; [ForUpdate] ) StatementNoShortIf

ForInit:
  StatementExpressionList 
  LocalVariableDeclaration

In other words: the first bit of the for can contain either a list of statement expressions, or local variable declarations, but not both.

  • System.out.println("hi") is a statement expression (because it's a method invocation expression);
  • int i=0 is not a statement expression (because it's not an expression);
  • i=0 is a statement expression, because it's an assignment.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=114845&siteId=1