View Single Post
Old 06-04-2006, 11:31 PM   #1 (permalink)
j.gohel
Code Monkey
 
Join Date: Apr 2005
Posts: 68
j.gohel is on a distinguished road
A simple ambiguity regarding the thing that in java everything is passed by copy??

Hi,

I have read that java passes-by-copy everything.But the behaviour of the following code i am not able to understand:


Code:
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
j.gohel is offline   Reply With Quote