final variable in a for loop

A

Alessio

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
 
L

Lew

Alessio said:
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? :)

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>
 
C

Christian

Alessio said:
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
you may not assign a new value within the loop to i if i is final
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,999
Messages
2,570,243
Members
46,835
Latest member
lila30

Latest Threads

Top