Java is pass-by-value. Let's start simple, with ints:
int x = 5;
changeIt(x);
System.out.println(x); // this prints.. 5. always.
public void changeIt(int x) {
// x is local to this method. It is created when this method begins..
x = 10;
// and now x just goes away. I set to '10' a thing that disappears here..
// Therefore this method does nothing useful whatsoever!
// in the caller context? x is.. still 5. I modify my own copy, not yours.
}
PBV means that what the code passes to the changeIt
method is the value 5. NOT 'x' or the location of 'x' or in any other way you care to put the notion 'x, the variable'.
Now, for all non-primitives (only int, float, double, long, boolean, char, short, and byte are primitive. All other types are non-primitive), the 'value' is the REFERENCE. A reference is a treasure map to the treasure. Strings are non-primitive, so with:
String x = "Hello";
// x is a treasure map.
//If you follow the map, it leads to the treasure 'Hello'.
x.toLowerCase(); // the dot operator is: "Follow the treasure map"
x = "Goodbye"; // this makes a new treasure map..
// x is a treasure map; it has been wiped out and overwritten with a map to "Goodbye".
changeIt(x); // this makes a copy of the _TREASURE MAP_. Not the treasure.
Now, if I have a treasure map, and I make a copy of it and hand you the treasure map, and you use your copy of the map and tear it to pieces, my map does not change.
However, if you follow your treasure map to the treasure and empty out the box, and later I follow my map, I'll find... that all the treasure has been taken.
Now, string is a kind of treasure that is impervious ot change. It is a so-called 'immutable'. You can recognize them as follows: No method on them changes it. For example, someString.toLowerCase()
makes a NEW string; it does not modify it. No method modifies it.
Therefore, there is no way to do what you want here either. To change things, you make a new treasure and return a new treasure map. This DOES work:
String x = "Hello";
x = changeIt(x); // update my map!
public String changeIt(String x) {
return x.toLowerCase(); // make a new treasure, then a new map, and return that.
}
however, if you have a mutable object, passing a copy of a treasure map CAN lead to change. Example:
List<String> list = new ArrayList<String>();
list.add("Hello");
System.out.println(list); // prints [Hello]
changeIt(list);
System.out.println(list); // prints [Hello, World]
void changeIt(List<String> list) {
//list is a copy of the treasure map.
list.add("World");
// but '.' is the: Follow the treasure map operator.
// I went to the treasure and put a new item in the box.
// THAT is visible to the caller!
list = null; // but this is not; I am wiping out MY copy of the map.
}