Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / October 2007

Tip: Looking for answers? Try searching our database.

final variable in a for loop

Thread view: 
Alessio - 17 Oct 2007 16:01 GMT
Hi to everyone. Sorry if this question has been asked before...
Is something like the code below legal? if yes, which are the
implications of making the variable i final?

for(final int i = 0; i < something; ++i) {
 new AnonymousInnerClass() {
   public void doSomething() {
     ...use i in some very creative way...
   }
 };
}

This code appears to work for me, but actually I would have expected
it to be in error since the loop might assign a new value to i on each
iteration, and the final keyword should forbid that. Am I missing
something? Will this code eventually make the computer explode? :)

Thanks for any insight on this...

cheers
Alessio Stalla
Lew - 17 Oct 2007 16:11 GMT
> Hi to everyone. Sorry if this question has been asked before...
> Is something like the code below legal? if yes, which are the
[quoted text clipped - 12 lines]
> iteration, and the final keyword should forbid that. Am I missing
> something? Will this code eventually make the computer explode? :)

There are special rules for for() loops.  Give them a go; maybe you'll find it
easier to parse what they're saying than I do:

<http://java.sun.com/docs/books/jls/third_edition/html/defAssign.html#16.2.12>
<http://java.sun.com/docs/books/jls/third_edition/html/defAssign.html#16.2.4>
as they pertain to
<http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.12.4>

Signature

Lew

Christian - 17 Oct 2007 16:11 GMT
Alessio schrieb:
> Hi to everyone. Sorry if this question has been asked before...
> Is something like the code below legal? if yes, which are the
[quoted text clipped - 17 lines]
> cheers
> Alessio Stalla

you may not assign a new value within the loop to i if i is final
Alessio - 17 Oct 2007 16:16 GMT
never mind. Indeed it does not work, as I suspected.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.