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 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);
}
}