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
The s1 and s2 variables in your function swap are local to that function.
You need to define s1 and s2 as private variables for your class, or return an array of strings from your function.
The following code is a NoGo, never implement this anti pattern, never ever ever ever change private final internals on immutable objects. Don't blame me for showing this hack, blame Oracle's jvm for not disallowing it.
But, if one day you find some code where this works:
String a = "Hello";
String b = "World";
String c = "World";
swap(a,b);
System.out.printf("%s %s%n", a,b); // prints: World Hello !!
System.out.println(c); // Side effect: prints "Hello" instead of "World"....
the implementation of swap
could look like this: (read on your own risk, I warned you!)
private void swap(String a, String b) {
try {
Field value = String.class.get("value");
value.setAccessible(true); // this should be forbidden!!
char[] temp = value.get(a);
value.set(a, value.get(b));
value.set(b, temp); // Aaargh, please forgive me
} catch(Exception e) {
e.printStackTrace(e);
}
}
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.