Search code examples
javaarraylistfinal

Why can Java final array variable be modified?


I know that writing a lambda in Java 8 to use a variable requires final type, but why can a variable of final array type be modified?

public static void main(String[] args) {
        final String[] prefix = {"prefix_"};
        String suffix = "_suffix";

        List<Integer> list = Arrays.asList(1005, 1006, 1007, 1009);
        List<String> flagList = list.stream().map(param -> {
            prefix[0] = "NoPrefix_";
            String flag = prefix[0] + param + suffix;
            return flag;
        }).collect(Collectors.toList());

        System.out.println(flagList);

        System.out.println(prefix[0]);
    }
    

result:

[NoPrefix_1005_suffix, NoPrefix_1006_suffix, NoPrefix_1007_suffix, NoPrefix_1009_suffix]
NoPrefix_


Solution

  • So a final array means that the array variable which is actually a reference to an object, cannot be changed to refer to anything else, but the members of the array can be modified

    refer below link for more information. https://www.geeksforgeeks.org/final-arrays-in-java/

    As per description for example

    final String[] arr = new String[10];
    list.stream().map(ele -> {
    
        arr[0] = ele.getName(); // this will work as you are updating member of array
        arr = new String[5]; // this will not work as you are changing whole array object instead of changing member of array object.
    
    }).collect(Collectors.toList());
    

    the same thing happen when you use any final collection there.