JohnSmith
JohnSmith

Reputation: 4678

strings and memory allocation in java?

one thing that i always wondered, if i have a method like this:

String replaceStuff (String plainText) {
        return plainText.replaceAll("&", "&");
}

will it create new String objects all the time for the "&" and the "&" that gets destroyed by the GC and then recreated again by next call? E.g. would it in theory be better to do something like this

final String A ="&";
final String AMP ="&";

    String replaceStuff (String plainText) {
            return plainText.replaceAll(A, AMP);
    }

i think this is probably a more theoretic question than a real life problem, I am just curious how the memory management is handled in this aspect.

Upvotes: 0

Views: 597

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1499770

No. String literals are interned. Even if you use an equal literal (or other constant) from elsewhere, you'll still refer to the same object:

Object x = "hello";
Object y = "he" + "llo";

System.out.println(x == y); // Guaranteed to print true.

EDIT: The JLS guarantees this in section 3.10.5

String literals-or, more generally, strings that are the values of constant expressions (§15.28)-are "interned" so as to share unique instances, using the method String.intern.

Section 15.28 shows the + operator being included as an operation which can produce a new constant from two other constants.

Upvotes: 4

Sathwick
Sathwick

Reputation: 1331

Strings are handled little different than the normal objects by GC. For example if

String a = "aaa"; String a1 = "aaa";

Now both a and a1 will point to same String value in memory till any of the value changes. Hence there will be only 1 object in memory.

Also, if we change 'a' and 'a1' to point to any other string, still the value "aaa" is left in the string pool and will be used later by JVM if required. The string is not GC'd

Upvotes: 1

Michael Berry
Michael Berry

Reputation: 72254

Nope, they're literals and therefore automatically interned to the constant pool.

The only way you'd create new strings each time would be to do:

String replaceStuff (String plainText) {
   return plainText.replaceAll(new String("&"), new String("&"));
}

Upvotes: 3

Related Questions