This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes funny Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "funny "for loop"" Watch "funny "for loop"" New topic

funny "for loop"

Lucas Smith
Ranch Hand

Joined: Apr 20, 2009
Posts: 804

Does not compile:

Compiles fine:

I think that compiler wants to prevent us - the first statement is useless - we do not do anything with int - just declaring, but when we add curly braces the situation is different. We have THE SCOPE of an int in which that variable can be used, so compier doesn't give any error.

Am I right?
Correct me if I am wrong.

Henry Wong

Joined: Sep 28, 2004
Posts: 18542

Short answer.... it is simply defined that way. The JLS defines the body of a ForStatement as having a Statement. A LocalVariableDeclaration is *not* one of the options of Statement, hence, illegal for the first case. In the second case, a BlockStatement is an option for Statement, and a BlockStatement is defined to contain LocalVariableDeclarations, hence, legal.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
It is sorta covered in the JavaRanch Style Guide.
subject: funny "for loop"
Similar Threads
Trouble trying to increase the scale of my program
Simple Gui Question (Head First Java)
ColorTable Array!!
java graphic problem
Can I do this with a Switch case?