A simple ambiguity regarding the thing that in java everything is passed by copy
Hi,
I have read everywhere that java passes-by-copy everything.But the behaviour of the following code i am not able to understand:
import java.util.*;
public class Test1
{
public static void main(String[] args)
{
ArrayList list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
func(list);
System.out.println("Arr1 --> " + list);
}
static void func(ArrayList arr)
{
arr.add("4");
arr.add("5");
arr.add("6");
System.out.println("Arr2 --> " + arr);
}
}
It o/p is:
C:\JIGNESH_GOHEL\JigneshG\JavaProgs>java Test1
Arr2 --> [1, 2, 3, 4, 5, 6]
Arr1 --> [1, 2, 3, 4, 5, 6]
But it should be somewhat like this as per my understanding(correct me if am wrong)
Arr2 --> [4, 5, 6]
Arr1 --> [1, 2, 3]
So can i get the explaination why this is happening??
It seems the arraylist object is passed by reference
[1033 byte] By [
j.gohel] at [2007-11-11 8:50:14]

# 1 Re: A simple ambiguity regarding the thing that in java everything is passed by copy
I don't know what you've been reading. In Java, all parameters are passed by reference EXCEPT the primitive data types (int, char, byte, etc.). All non-primitive data type memory reference is indirect - the "data" for the object is stored "on the heap" while the variable points to a location "on the stack" which points to the object on the heap. What you observed is correct.
nspils at 2007-11-11 22:34:20 >

# 2 Re: A simple ambiguity regarding the thing that in java everything is passed by copy
You're both sort of right. What java technically passes is a copy of the memory address (reference) of the object.
So any changes you make on an object inside a function are shown outside of it, however, assigning a new object to that reference wont be seen.
the variable "object" will not change after this method call because you're assigning a new object to the copied reference. (i'm not very good at explaining this am i?)
MyObject object = new MyObject("13");
public void stuff(MyObject obj)
{
obj = new MyObject("42");
}