Is the following code safe in Java? My concern is due to the fact that in function f()
variable arr
is allocated on stack and as such is deallocated upon leaving the scope but is still referred to outside the scope.
public class Main {
public static class Array {
public final int[] arr;
public Array(int arr[]) {
this.arr = arr;
}
}
public static Array f() {
int arr[] = {1, 2, 3};
return new Array(arr);
}
public static void main(String[] args) {
Array a = f();
System.out.println(a.arr[0]);
System.out.println(a.arr[1]);
System.out.println(a.arr[2]);
}
}