Strings are immutable objects
A String is an object that holds a sequence of characters. It is immutable: once created, its characters never change. Every method that looks like it modifies a String — toUpperCase(), replace(), trim() — actually returns a new String and leaves the original alone. If you do not store the result, the work is thrown away.
public class Main {
public static void main(String[] args) {
String name = "asha";
name.toUpperCase(); // result ignored: name is unchanged
System.out.println(name);
String upper = name.toUpperCase(); // keep the new String
System.out.println(upper);
name = name + " khan"; // + builds a new String too
System.out.println(name);
System.out.println(name.length());
}
}asha
ASHA
asha khan
9Call name.replace("a", "@") without assigning it, print name, then assign it and print again.
HashMap keys and safe to pass between threads.