I am a Java beginner. I am trying to change the third element value of only "array1" within the object "ta". However, "arr1" is also getting updated even though I do not believe I changed it and I do not intend to change it. I am unable to understand why this is happening.
public class testArrays {
private int array1[] ;
public testArrays(int[] arr) {
this.array1 = arr;
}
public String toString(String name, int arr[]) {
String outStr = "[";
for (int i=0; i<= arr.length-1; i++) {
if(i < arr.length-1)
outStr = outStr + arr[i] + ", ";
else
outStr = outStr + arr[i] + "]";
}
return name + " = " + outStr;
}
public static void main(String[] args) {
int arr1[] = {1, 2, 3, 4, 5, 6, 7};
testArrays ta = new testArrays(arr1);
System.out.println(ta.toString("arr1 Before ",arr1));
System.out.println(ta.toString("ta.array1 Before ", ta.array1));
ta.array1[2] = 333;
System.out.println(ta.toString("arr1 After ",arr1));
System.out.println(ta.toString("ta.array1 After ", ta.array1));
}
}
Here's the output:
arr1 Before = [1, 2, 3, 4, 5, 6, 7]
ta.array1 Before = [1, 2, 3, 4, 5, 6, 7]
arr1 After = [1, 2, 333, 4, 5, 6, 7]
ta.array1 After = [1, 2, 333, 4, 5, 6, 7]
I have used debugger to trace my steps, but after line 33 both arr1 and ta.array1 are getting updated instantaneously.
Here's the output I was expecting:
arr1 Before = [1, 2, 3, 4, 5, 6, 7]
ta.array1 Before = [1, 2, 3, 4, 5, 6, 7]
arr1 After = [1, 2, 3, 4, 5, 6, 7]
ta.array1 After = [1, 2, 333, 4, 5, 6, 7]