Java passes references by value; swapping references in the method being called has no effect in the caller. Your strings are immutable, so there is nothing you can do to them in the swap
method that would be visible to the caller.
If you pass mutable objects, however, you will see that changes to them made in the swap
would reflect in the original:
public static void main(String[] args) {
String a[] = {"hello", "world"};
swap(a);
System.out.println(a[0] + " " + a[1]);
}
static void swap(String[] a) {
String t = a[0];
a[0] = a[1];
a[1] = t;
}
This works, because array is mutable (i.e. changes can be made to its state), and because a reference to the original object is passed to the function being called (by value). When swap
modifies the content of its a
, the content of a
in the caller gets modified too, because it is the same object.