Search code examples
javafinal

Strange Behavior in final variable in Java


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);
    }
}

Solution

  • 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.