John
John

Reputation: 2782

String memory allocation in java

In an Servlet class, I am having the checks

if("Mail".equals( request.getParameter(mode)) || "Chat".equals( request.getParameter(mode))) {}

My question is about the memory allocated for the strings "Mail" and "Chat". Will it create new string objects for every request to this servlet. What about GC?.

Upvotes: 2

Views: 1236

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500515

No, it won't create a new object each time. String constants are interned - they're created once and put in a special pool.

Not only will it not create a new string each time you run the code, but if you use the constants "Mail" or "Chat" elsewhere in your code, they'll use the same string objects too.

From the Java Language Specification section 3.10.5:

Each string literal is a reference (§4.3) to an instance (§4.3.1, §12.5) of class String (§4.3.3). String objects have a constant value. 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.

Upvotes: 6

Related Questions