A simple ambiguity regarding the thing that in java everything is passed by copy??
I have read everywhere that java passes-by-copy everything.But the behaviour of the following code i am not able to understand:
public class Test1
public static void main(String args)
ArrayList list = new ArrayList();
System.out.println("Arr1 ---> " + list);
static void func(ArrayList arr)
System.out.println("Arr2 --> " + arr);
It o/p is:
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
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.
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");
Yes - I have to correct what I said before. The Java method of passing variables is "pass by VALUE" - where the value of all but primitive data types is a memory location (a reference), so the passing of an object is "as if it were" "pass by reference".
Last edited by nspils; 06-06-2006 at 09:46 AM.
By Mike Tsakiris in forum .NET
Last Post: 10-04-2002, 05:32 PM
By zfqjava in forum java.announcements
Last Post: 01-08-2002, 04:26 AM
By Dharmesh in forum .NET
Last Post: 10-01-2001, 03:47 PM
By Craig in forum Architecture and Design
Last Post: 04-22-2001, 01:04 PM
Last Post: 03-21-2001, 04:01 PM
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL