3

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?

Sadık
  • 4,249
  • 7
  • 53
  • 89

1 Answers1

2

I know of no way to avoid creating a String object in your toString(), but you can avoid retaining these new strings (all but the first one become eligible for GC after the method execution) by explicitly calling String.intern():

@Override
public String toString() {
    return new String(this.names).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.

ernest_k
  • 44,416
  • 5
  • 53
  • 99