File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help with FOR

 
sumaraghavi ragha
Ranch Hand
Posts: 118
  • 0
  • 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: 20393
46
Chrome Eclipse IDE Java Windows
  • 0
  • 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
Pie
Posts: 12022
25
Chrome Java Linux
  • 0
  • 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
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks lot both of you
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic