wood burning stoves
The moose likes Beginning Java and the fly likes for loop.. is this legal? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "for loop.. is this legal?" Watch "for loop.. is this legal?" New topic

for loop.. is this legal?

YekSoon Lok

Joined: Nov 29, 2001
Posts: 4
this is actually from JavaRanch ...
is this legal?
int i;
for(i=4, int t=6; i<0; i++)
Rob Ross

Joined: Jan 07, 2002
Posts: 2205
You could actually try compiling this code yourself and see if you get any errors


SCJP 1.4
Younes Essouabni
Ranch Hand

Joined: Jan 13, 2002
Posts: 479
I think it's legal. Don't see the trap! Why won't it be legal?
It just won't do a thing!!!
[ February 07, 2002: Message edited by: Younes Essouabni ]

By constantly trying one ends up succeeding. Thus: the more one fails the more one has a chance to succeed.
YekSoon Lok

Joined: Nov 29, 2001
Posts: 4
the answer posted by JavaRanch is:
You can declare or initialize more than one variable in a for loop, but you can't mix declaration with initialiazation.

any idea what it means?
Junilu Lacar

Joined: Feb 26, 2001
Posts: 6529

In the code
int i;
for(i=4, int t=6; i<0; i++)
i=4 is an initialization while
int t=6 is a declaration/initialization
This does not conform with the valid syntax for the ForInit part mentioned in the JLS, which should be in the form of a local variable declaration. See the specifications for local variable declaration statements (JLS �14.4).
Here's one that does work though (for illustration purposes only):

Junilu - [How to Ask Questions] [How to Answer Questions]
I agree. Here's the link: http://aspose.com/file-tools
subject: for loop.. is this legal?
It's not a secret anymore!