I am trying to swap two strings in Java. I never really understood "strings are immutable". I understand it in theory, but I never came across it in practice.
Also, since String is an object in Java and not a primitive type, I don't understand why the following code prints the same result twice, instead of interchanging the words!
public static void main(String[] args)
{
String s1 = "Hello";
String s2 = "World";
System.out.println(s1 + " " + s2);
Swap(s1, s2);
System.out.println(s1 + " " + s2);
}
public static void Swap(String s1, String s2)
{
String temp = s1;
s1 = s2;
s2 = temp;
}
I want it to print
Hello World
World Hello
But it is printing
Hello World
Hello World
I thought s1 and s2 are references and hence the references should be swapped and the new ones should point to the other one respectively. Where am I going wrong?
I thought s1 and s2 are references and hence the references should be swapped and the new ones should point to the other one respectively.
Yes. Locally inside swap
, this is exactly what happens.
However, s1
and s2
are copies of the references passed into the function, so the effect remains local. Note that it’s not the strings that are copied (since String
is a reference type). But the references are copied.
… and since parameter references are always copied in Java, writing a swap
function according to your specifications is, quite simply, not possible.
If you have problems understanding the difference, consider this: you want to write a letter to a friend so you copy her postal address from your address book onto an envelope. By this process, you certainly didn’t copy her home (copying a whole house is a bit difficult in practice) – you only copied the address.
Well, an address refers to her home so it’s exactly like a Java reference.