public class Demo1 {
public static void main(String[] args) {
int arr[] = {2, 3, 4};
sort(arr);
System.out.println(Arrays.toString(arr));
}
public static void sort(int arr[]) {
int arr1[] = {0, 3, 4};
arr = Arrays.copyOfRange(arr1, 0, arr1.length);
}
}
Output: [2, 3, 4]
In this code snippet, I expected the array arr to be modified by calling the sort method and then print the modified result. However, the output still shows the original array [2, 3, 4].
This is because in Java, when you pass an array to a method, you are actually passing the reference (memory address) of the array. Inside the sort method, when you reassign arr to point to a new array arr1, it only affects the local variable arr and does not change the original array in the main method.
Solution:#
- Modify the array referenced by this reference
public class Demo1 {
public static void main(String[] args) {
int arr[] = {2, 3, 4};
sort(arr);
System.out.println(Arrays.toString(arr));
}
public static void sort(int arr[]) {
// Modify the arr array directly inside the sort method
arr[0] = 0;
arr[1] = 3;
arr[2] = 4;
}
}
- Change the return type of sort to int[], then modify it in the main method
public class Demo1 {
public static void main(String[] args) {
int arr[] = {2, 3, 4};
arr = sort(arr);
System.out.println(Arrays.toString(arr));
}
public static int[] sort(int arr[]) {
int arr1[] = {0, 3, 4};
return Arrays.copyOfRange(arr1, 0, arr1.length);
}
}