Search code examples
javainner-classes

Java accessing local array from inner class


I know that you cant edit an local variable from a inner class, if the variable isnt final. But why can I make change to an array from an innerclass eventhough it isnt final?

 public void test(String s) {
        int a[] = {1};
        IntStream.range(0, s.length() / 2).forEach(i -> a[0] = 2);
}

If a is an array, compiler doesnt complain if I edit it. But if a was an integer, I cant do changes to it in inner class.


Solution

  • This is a usable trick in Java because the array (which is an object) you are using is never reassigned. You could do the same with the properties of an object. If you changed properties of an object, you would still not have reassigned an object and it would remain "effectively final". Reference: Effectively final - Inner classes access

    A side note: it is preferable to write arrays in the form: "int[] a" because they are more readable.