Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

is this final variable modified

 
venu surampudi
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Stevi Deter
Ranch Hand
Posts: 265
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Deepak Chopra
Ranch Hand
Posts: 433
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ram Manoj
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 189
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);}
 
Stevi Deter
Ranch Hand
Posts: 265
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ram,

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

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic