When creating a String like this:
String s1 = “ABC”
the JVM will look in the String pool if "ABC" exists there and create a new object only if "ABC" doesn't exist yet.
So the usage of
String s1 = new String("ABC")
halts this behavior and will create an object every time.
Now I have a problem when converting a char array to String:
private char[] names;
...
@Override
public String toString() {
return new String(this.names);
}
This will always create a new object. Can I convert from char array to String without creating a new object each time?
I know of no way to avoid creating a
Stringobject in yourtoString(), but you can avoid retaining these new strings (all but the first one become eligible for GC after the method execution) by explicitly callingString.intern():And you can test it by repeatedly checking
myObject.toString() == myObject.toString().But before doing this, do yourself a favor and be aware of what you're doing. It's possible that generating a string object is the better choice, depending on your main reason for doing this.