Code:
public class Solutions {
public static void increment(int[] arr) {
int[] arr1 = {1, 2, 3, 4, 5};
arr = arr1;
for (int i = 0; i < 5; i++) {
arr[i]++;
}
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
increment(arr);
for (int i = 0; i < 5; i++) {
System.out.print(arr[i] + " ");
}
}
}
Output: 1 2 3 4 5
Explanation provided:
Here the changes done in main didn’t reflect. Although here as well the reference
to the array was passed, but in the first line inside function we created another
arry of size 5 and made arr refer to that array(without affecting array created in
main). Thus the changes this time won’t reflect
My question is once the reference has been changed how can we even access the previous array that is in main as now arr is referring to arr1 ? Therefore we are printing now arr1 isn't it?