File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes is this final variable modified Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "is this final variable modified" Watch "is this final variable modified" New topic

is this final variable modified

venu surampudi

Joined: Jan 03, 2008
Posts: 16

In the new for construct assuming that a is an integer array

for (final int v: a){

why does java allow us to declare the iteration variable to be final and not complain? doesent it (v) change after every iteration?


If you wanna be cocky you better be kobe !
Stevi Deter
Ranch Hand

Joined: Mar 22, 2008
Posts: 265

This question has been addressed very recently in this very forum.

The short answer is: a new final variable is created on each pass through the for loop.

There will always be people who are ahead of the curve, and people who are behind the curve. But knowledge moves the curve. --Bill James
Deepak Chopra
Ranch Hand

Joined: Jul 23, 2007
Posts: 433

Venu, i want to ask you a very simple question :
when you declare a variable inside a "for loop", at which point it scope finishes.

Answer to this question is, answer to your question.

I hope it will work, if you still face any problem feel free to put your doubt on the forum.

Thanks and Regards,
SCJP 1.5 (90%), SCWCD 1.5 (85%), The Jovial Java, java.util.concurrent tutorial
Ram Manoj
Ranch Hand

Joined: Jan 12, 2008
Posts: 52
I can understood the reason why the following will compile even though 'v' is final.

And the following cannot be used as a normal 'for' construct

But any ideas on why is that the new 'for' construct is designed so, that it creates a new variable on every iteration.
Mamadou Touré
Ranch Hand

Joined: Dec 27, 2007
Posts: 189

In the first example you are just printing the value of V (you don't modify it), so it's ok. But in the second example, you modify the value of V (by incrementing it V++), so that's why the compiler complains


for (final int v: a){System.out.println(v);}


And the following cannot be used as a normal 'for' construct


for (final int v=0;v<a.size(); v++){System.out.println(v);}

SCJP 5 (76%)
SCWCD 5 (86%)
SCBCD 5(70%)
"The greatest glory in living lies not in never falling, but in raising every time we fall.".. Nelson Mandela
Stevi Deter
Ranch Hand

Joined: Mar 22, 2008
Posts: 265


It should be clearer if you realize that the foreach (enhanced for loop) is the equivalent of saying:

I agree. Here's the link:
subject: is this final variable modified
It's not a secret anymore!