Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

for loop.. is this legal?

 
YekSoon Lok
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is actually from JavaRanch ...
==
is this legal?
int i;
for(i=4, int t=6; i<0; i++)
===
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could actually try compiling this code yourself and see if you get any errors

Rob
 
Younes Essouabni
Ranch Hand
Posts: 479
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
YekSoon Lok
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the answer posted by JavaRanch is:
===
No.
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
Bartender
Posts: 7594
53
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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):
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic