0

In my java program i have used one final variable.We know that the value of any final variable is fixed and can't be changed.so why this particular program is working fine?Can anyone explain.

public static void main(String args[])
{
    int[] integerArray = { 1, 2, 3, 4, 5 };

    for (final int j : integerArray) {
    System.out.println(j);
    }
}
Chiradeep
  • 973
  • 12
  • 32

7 Answers7

3

It's final within the body of the loop - but you're effectively declaring a different variable for each iteration of the loop.

It's as if you'd written this:

for (int i = 0; i < integerArray.length; i++) {
    final int j = integerArray[i];
    System.out.println(j);
}

Again, we have a "new" local variable called j on each iteration of the loop... but each of those variables never changes its value.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

You are iterating through the array and printing the values, but you are not attempting to change that final int j during the iteration.

A new final int j is defined at every step of the iteration. You are not overriding the value in an existing final reference.

Doing something like:

 for (final int j : integerArray) {
    j = 5; // this is a direct override, you won't be able to do this.
    System.out.println(j);
 }
flavian
  • 28,161
  • 11
  • 65
  • 105
1

Because in the for-loop j is declared as int j. Which means for every iteration, a new j will be created and its scope is the for-loop.

Now each j is initialized only once, which adheres to final keyword. Now the below code generates compilation error

  for (final int j : integerArray) {
        System.out.println(j);
        j=0; // error, j is getting initialized twice in for-loop context
   }
sanbhat
  • 17,522
  • 6
  • 48
  • 64
1

Your enhanced for loop is equivalent to this:

for (int index = 0; index < integerArray.length; index++) {
  final int j = integerArray[index];
  System.out.println(j);
}

As you can see, there is no contradiction here.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
1

The actual effective code is something like this :

for (for j=0;j < integerArray.length ; j++ )
{
    final int i = integerArray(j); // declaring final i for each iteration
    System.out.println(i);

}
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
0

For each iteration, you are declaring a new final variable. It works fine because you are not changing that variable.

bkrcinar
  • 345
  • 1
  • 7
0

On each iteration it declares new variable. So this is not strange behaviour.

eatSleepCode
  • 4,427
  • 7
  • 44
  • 93