Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help with FOR

 
sumaraghavi ragha
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why the following rogram showing difference when we braces in the 2nd for loop

class Ex2
{
public static void main(String[] args)
{
int i,j;
for (i=0;i<2 ;i++ )
{
for(j=0;j<2;j++)
System.out.println("j value is" + j);
System.out.println("i value is" + i);
}
}
}


please tell me why when i insert braces for 2nd for loop like below
class Ex2
{
public static void main(String[] args)
{
int i,j;
for (i=0;i<2 ;i++ )
{
for(j=0;j<2;j++)
{
System.out.println("j value is" + j);
System.out.println("i value is" + i);
}
}
}
}

in the first program we don't have any braces for 2 nd for loop
even though it is the first for loop so it has to execute all the statements but it is not doing that why so?
 
Rob Spoor
Sheriff
Pie
Posts: 20531
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With code blocks and identation (where all code from the same level has the same indentation), you immediately see what is going on:

As you can see, in the first part, the body of the inner for loop is only one statement and the second printing occurs in the outer loop, whereas it's two statements in the second part.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12125
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a 'for' loop (note: there is no such thing as FOR in java) can have one of two things after it - a statement, or a block. a block is enclosed in braces: {}. if there are no braces, the one-and-only-one statement is in the body of the loop.

when you removed the braces, as Rob points out, only one of your print statements is inside the inner loop.
 
sumaraghavi ragha
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks lot both of you
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic