| Author |
is this final variable modified
|
venu surampudi
Greenhorn
Joined: Jan 03, 2008
Posts: 16
|
|
ranchers, In the new for construct assuming that a is an integer array for (final int v: a){ System.out.println(v); } why does java allow us to declare the iteration variable to be final and not complain? doesent it (v) change after every iteration? Thanks venu
|
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
|
 |
Sunny Jain
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
|
|
Hi, 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 code: -------------------------------------------------------------------------------- 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
|
|
Ram, It should be clearer if you realize that the foreach (enhanced for loop) is the equivalent of saying:
|
 |
 |
|
|
subject: is this final variable modified
|
|
|