aspose 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


Win a copy of Java 8 in Action this week in the Java 8 forum!
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: 19552
    
  16

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: 10924
    
  12

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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Help with FOR
 
Similar Threads
Nested for Loop doubt?
I am not getting the required output...
for loop construct - Marcus Green Exam1,Q21
please help with text formating in java
A Basic For Loop??