Java is always pass-by-value. What you are describing is passing the object reference by value.
There is a key distinction here. You are not passing the object as a reference, so the reference link is broken as soon as you assign a new instance to your parameter. As long as the reference value remains the same, altering the contents of an object passed in will persist when you return back to the caller. Another key difference is that a reference value can be null
... but null
is not an object - so how can you reference the absence of an object?
If you want to create a new object, you will need to copy the existing one. The copy should be performed inside the method to ensure the operation is consistent.
For simple objects (objects with a shallow class hierarchy, like the example below), you can usually get by with a basic copy constructor:
class Album {
private String title;
private String artist;
public Album(Album copy) {
this.title = copy.title;
this.artist = copy.artist;
}
}
This will allow you to copy the object inside your method:
public void copyAlbum(Album album) {
album = new Album(album); // Clone the album passed in
}
For more complex object graphs, you may want to use a library such as Orika or Dozer to accurately create a deep copy of your object. This question has some useful advice on copying objects in Java.