2

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?.

1
  • If you ever traced the amount of code executed just schedulaing a servlet you would not worry about such micro optimisations! Commented Nov 12, 2010 at 7:14

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Jon, In some other thread I asked you "" does it also get stored in pool , and how much memory it consumes. I would like to know
@org.life.java: Yes, it does get stored in the pool. It won't take up much memory - enough for an empty char array and the String object itself, basically.
So it only makes sense to store Strings as static final if you use them a lot in your class and don't want to risk typos, right?
@cringe: In terms of memory usage, yes. But keeping consistency is pretty important...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.