| Author |
Help with FOR
|
sumaraghavi ragha
Ranch Hand
Joined: Nov 17, 2006
Posts: 118
|
|
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
Joined: Oct 27, 2005
Posts: 19216
|
|
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.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 9948
|
|
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.
|
Never ascribe to malice that which can be adequately explained by stupidity.
|
 |
sumaraghavi ragha
Ranch Hand
Joined: Nov 17, 2006
Posts: 118
|
|
|
Thanks lot both of you
|
 |
 |
|
|
subject: Help with FOR
|
|
|