File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Help with FOR Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Help with FOR" Watch "Help with FOR" New topic
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: 19654
    
  18

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 - OCEEJBD 6
How To Ask Questions How To Answer Questions
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11161
    
  16

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.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
sumaraghavi ragha
Ranch Hand

Joined: Nov 17, 2006
Posts: 118
Thanks lot both of you
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Help with FOR
 
Similar Threads
Nested for Loop doubt?
for loop construct - Marcus Green Exam1,Q21
A Basic For Loop??
I am not getting the required output...
please help with text formating in java