why outer for loop variable can’t be used in inner for loop Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of why outer for loop variable can’t be used in inner for loop without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am writing following code:

int j =0;
for( j=0; j< 10;j++){
  System.out.println("Printing outer for loop :" +j);
  for(j; j < 8; j++)
  {
     System.out.println("Printing inner for loop" + j);
  }
}

Eclipse showing me following error:

Syntax error on token "j", ++ expected after this token

I don’t understand the reason behind. Any explanation would be appreciated. Thanks

Answer

As defined in JLS, the first “part” of the for loop declaration, ForInit, is a list of statement expressions or a local variable declaration; j isn’t a statement expression (an assignment; a pre/post increment/decrement; a method invocation; a new class initialization) or a local variable declaration, so it’s invalid syntax.

Depending upon what you are trying to do, you can just omit it:

for (; j < 8; j++)

Note that all of the three “parts” of the for loop are optional: for instance, this is fine:

for (;;) {
}

(It’s just an infinite loop)

We are here to answer your question about why outer for loop variable can’t be used in inner for loop - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji