• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

Why final variable in enhanced for isn't acting final?

 
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


What's the output and why? (choose all that apply)

A) Compilation fails because Integer is a reserved keyword
B) Compilation error (attempting to re-assingn a final varialble)
C) 234
D) 2340
E) Runtime Exception
F) Other

Why is the answer D? Doesn't "final" modifier on Line 222 makes it impossible to re-assign "i"?
[ June 10, 2006: Message edited by: Firas Zureikat ]
 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


The enhanced for-loop as shown above is actually just syntactic sugar for something along the lines of:



That is, 'i' is a local variable (local to the for-loop) and it is not been assigned a value twice so it's just fine.

To finish this up. The following will *not* compile, because 'i' is assigned a value twice.

Assignment 1: the result of getCharArray(arr)[someindex].
Assignment 2: i = i+1
 
Firas Zuriekat
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, thanks..so it's just local variable and each iteration of the loop a new different final local variable is created.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!