• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic