Well, let's see an example.
public class Test {
public static class A {
public String str;
}
public static void main(String[] args){
A[] array = new A[1];
A a = new A();
a.str = "Hey";
array[0] = a;
a.str = "Hello";
System.out.println(a.str);
System.out.println(array[0].str);
}
}
However, the output is like this:
Hello
Hello
So, it is pass by reference? Actually, No.
Every object reference is storing the memory address of an object only. For example,
A a = new A();
a is storing the address of the block of memory space containing the newly created object. When it is put in the list,
array[0] = a;it is actually copying the address into the array.
It is easier to understand if we modify the above program to pass a primitive type value into the array:
public class Test {
public static void main(String[] args){
int a;
int[] array = new int[1];
a = 0;
array[0] = a;
a = 1;
System.out.println(a);
System.out.println(array[0]);
}
}
1
0
array[0] = a is actually copying 0 into array[0], so assigning new value to a will not affect the value of array[0].
No comments:
Post a Comment