public class TestingArray {
public static void main(String[] args) {
int iCheck = 10;
int j = iCheck;
j = 11;
System.err.println("value of iCheck "+iCheck);
int[] val1 = {1,2,9,4,5,6,7};
int[] val2 = val1;
val2[0] = 200;
System.err.println("Array Value "+val1[0]);
}
}
Output:
value of iCheck 10
Array Value 200
From the above code, I found that if any array val2 is being assigned to another array val1 and if we change any value of val2 array, the result is as well reflected for the array val1 while the same scenario is not with variable assignment.
Why?
The following statement makes
val2refer to the same array asval1:If you want to make a copy, you could use
val1.clone()orArrays.copyOf():Objects (including instances of collection classes,
String,Integeretc) work in a similar manner, in that assigning one variable to another simply copies the reference, making both variables refer to the same object. If the object in question is mutable, then subsequent modifications made to its contents via one of the variables will also be visible through the other.Primitive types (
int,doubleetc) behave differently: there are no references involved and assignment makes a copy of the value.