Hi all,

I was trying out this for loop example and i notice that the for loop only works for the printing of x.The printing of y value did not work at all until the loop ends. I am trying to understand how for loop actually works. Am i right to say that for loop will only work for the first line of statement after the loop statement?I understand that if i insert this {},everything in this code works fine because it is looping as a block of code each time. Please help me in understanding the concept of this,Thanks in advance.

  class ForLoop
  {
      public static void main(String args[])
      {
         int x,y;
         y = 20;

         for (x = 0; x < 5; x++)
            System.out.println("This is x:" + x);
            System.out.println("This is y:" + y);
            y = y - 2;
      }
  }

My output of the code above:

This is x:0
This is x:1
This is x:2
This is x:3
This is x:4
This is y:20
 for (x = 0; x < 5; x++)
    System.out.println("This is x:" + x);

When you do not use braces { } to demarcate your blocks (whether for if, for, when, whatever) then ONLY the next statement is part of that block.

there are two ways to end a for loop (not only for a for loop, btw, the same applies for if statements, ....
1. by using brackets. you can clearly tell the JVM where the scope lies:

for ( int x = 0; x < 5; x++){
// no matter how many lines of code are here, they're all in the loop until the matching closing bracket
// is reached
}

simply because there is no ambiguity: the compiler knows exactly what you mean.
2. without brackets, the first ';'
if you don't put brackets around your block, the JVM won't know what you want to loop over. so the scope of the loop will end when the first ; will be met:

for ( int x = 0; x < 5; x++);
System.out.println(" loop");
System.out.println(" loop ended");

both these print statements will only run once, since the first ';' is before the first print statement.

for ( int x = 0; x < 5; x++)
System.out.println(" loop");
System.out.println(" loop ended");

the first print statement will run 5 times, the second one only 1 time, after the loop has finished.

for ( int x = 0; x < 5; x++);
{
System.out.println(" loop");
System.out.println(" loop ended");
}

now both the print statements will be executed for each iteration of the loop.

Thanks for explaining the logic.Really help me in understand better on how it works.
:D

This question has already been answered. Start a new discussion instead.