From what I understand with Java, everything is passed by value. However, when you start talking about objects that contain other objects, everything becomes a little interesting, and I would like to be able to report it better and make sure that I fully understand. Therefore, I believe that only the primitives inside the object are actually copied, on the other hand, any objects that it contains ... the values โโof these objects are not copied, but are only copies of these links.
So, if we had some kind of object with these members
public class SomeObject { private String name; private String address; private List<String> friends; public SomeObject(String name, String address, List<String> friends) { this.name = name; this.address = address; this.friends = friends; } }
And we did it:
List<String> friendsList = new ArrayList<String>(); friendsList.add("bob"); friendsList.add("joe"); SomeObject so1 = new SomeObject("mike", "123 street", friendsList); friendsList.add("zoe"); friendsList.add("rick"); SomeObject so2 = new SomeObject("david", "300 ave", friendsList); System.out.println(so1.getName() + " " + so1.getAddress()); for (String friend : so1.getFriends()) { System.out.println(friend); } System.out.println(so2.getName() + " " + so2.getAddress()); for (String friend : so2.getFriends()) { System.out.println(friend); }
Our conclusion is this:
mike 123 street bob joe zoe rick david 300 ave bob joe zoe rick
Despite the fact that we created 2 separate objects, they both maintain a link to the original list of friends. That's why I worked a bit when people say that Java always passes by value.
source share