Thursday, March 6, 2008

The Secret Life of String ;-)

/mad scientist mode on

They always said "String is immutable - you cannot change its value without changing reference!"

But what They will say when I will use this code?
import java.lang.reflect.Field;

public class StringModificator {
public static void trueModificator(String str)
throws Exception {
Field valueField = str.getClass().getDeclaredField("value");
valueField.setAccessible(true);
char[] value = (char[])valueField.get(str);
char[] reversed = new char[value.length];
for (int idx=0; idx<value.length; idx++) {
reversed[idx]=value[value.length-idx-1];
}
for (int idx=0; idx<value.length; idx++) {
value[idx]=reversed[idx];
}
}

public static void falseModificator(String str) {
str="toster";
}

public static void main(String[] args) throws Exception {
String str = "it's a test";
String subStr = str.substring(3);
// prints "it's a test"
System.out.println(str);
System.out.println(subStr);

falseModificator(str);
// Still prints "it's a test"
System.out.println(str);
System.out.println(subStr);

trueModificator(str);
// But whats now? ;-)
System.out.println(str);
System.out.println(subStr);
}
}

So this whole String isn't so immutable as They said!!!

/mad scientist mode off

Similar postsbeta
Abuse of Booleans ;-)
How many i 1+1 in Java? ;-)
How to create valid file name?
Recursion is evil ;-)
How to get negative number from size() in LinkedList in Java? ;-)

No comments:

Post a Comment