aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes For Loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "For Loop" Watch "For Loop" New topic
Author

For Loop

Sabber bhatia
Ranch Hand

Joined: Jun 27, 2006
Posts: 59
class Hello
{
void method()
{
for(int x=0;x<4;x++)
int y=-1;
System.out.println(y);

}
}
class HelloDrive
{
public static void main(String[] args)
{
Hello h=new Hello();
h.method();
}
}

When i am compiling the above code
it's giving compile time error
1. '.class' expected
2. int y=-1;(Its not a statement)
But when i am doing
like

for(int x=0;x<4;x++)
{
int y=-1;
System.out.println(y);
}
Its not giving error
WHY
Nancy Antony
Ranch Hand

Joined: Sep 06, 2007
Posts: 145

When you are writing

for(int i=0;i<3;i++)
int y=-1;

then what is happening is : declaration statement becomes a part of a loop and y is declared again and again on the same local stack, hence error.

But when you say :
for(int i=0;i<3;i++){
int y=-1;
}

A new block is created and within block every time y is created and destroyed on entry and exit to the block , hence no error.
Sabber bhatia
Ranch Hand

Joined: Jun 27, 2006
Posts: 59
thanks KAN
horri khaled
Ranch Hand

Joined: Mar 24, 2008
Posts: 36
Hi
it works fine with me, I dont know where is the problem


SCJP 5
Nancy Antony
Ranch Hand

Joined: Sep 06, 2007
Posts: 145

Can you send the code ?
Sabber bhatia
Ranch Hand

Joined: Jun 27, 2006
Posts: 59
hey kan
i have a problem
I understand as you said "y is declared again and again in local stack"
but what if i will do like


for(int i=0;i<1;i++)
int y=-1
System.out.println(y);

Then same error is comming,Now only once y is declared in local stack as loop is executing once
Irina Goble
Ranch Hand

Joined: May 09, 2004
Posts: 91
Here

is a Local Variable Declaration Statement and it should appear within a Block.
Nancy Antony
Ranch Hand

Joined: Sep 06, 2007
Posts: 145

Even now also it is declared again and again as for loop has only one statement to be executed and that is int y=-1; (should end with semicolon, otherwise syntax error).

for( int i=0; i<3; i ++) ; // this semicolon tells the end of for loop this for loop has only one statement and that is null sattement that do nothing. We can create delay loops like this.

so

for(int i =0; i<3;i++) ;
int y=-1;

Now its valid as y will be declared only once, as it is not a part of for loop.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: For Loop