Since string is immutable I have to write as follows to remove all non-alphanemeric from the str.
void test(String str) {
str = str.replaceAll("[^a-zA-Z0-9\\s]", "").toLowerCase();
System.out.println("\n" +str);
}
What I couldn't understand is that how come it works by re-assigning to str?
Since String is immutable, I understand that if I assign it to a new String newString, they are pointing out two different objects, str and newString. That it, original string is pointing to str and modified string is pointing ot newStr which have two different immutable Strings. This is ok for me.
void test(String str) {
String newStr = str.replaceAll("[^a-zA-Z0-9\\s]", "").toLowerCase();
System.out.println("\n" +newStr);
}
But how come it works by reassigning to the same str object? Based on my understanding, it shouldn't be working since immutable str cannot me modified, so the result of the modified str cannot be stored in immutable str.
void test(String str) {
// this shouldn't be working based on my understanding. But it works. Why?
str = str.replaceAll("[^a-zA-Z0-9\\s]", "").toLowerCase();
System.out.println("\n" +str);
}
As you've seen the following image, string1 and string2 are pointing to the same String object in the heap. Could you clarify how this works internally?