Rama Krishna
Rama Krishna

Reputation: 1

When a methd returns a String , will it be a literal or a String object?

Lets say a method returns a String

String str = methodCall();

The return type of methodCall() is String.

Will we get a String literal which will be in pool memory or just a String object?

Upvotes: 0

Views: 359

Answers (2)

Stephen C
Stephen C

Reputation: 718788

When a method returns a String, will it be a literal or a String object?

This question is based on a misconception.

At runtime, every Java string is represented as a java.lang.String object. This includes string literals. In fact, it is (in general) impossible to distinguish a String object that originated from a string literal from one that originated some other way.

So ... basically ... the question in the title does not make sense.


Will we get a String literal which will be in pool memory or just a String object?

  1. It depends on how the string that you are returning was created.

  2. Not all objects in the string pool originated from string literals.

  3. Strings may be added to the string pool by calling String.intern. The JVM does this automatically when string literals are reified, but it doesn't do it automatically under any other circumstances.

So, the answer to the above will be that a string object returned by a method will be in the string pool if EITHER it started life as a string literal OR some application code put it there by calling String.intern.


Finally, note that the string pool is largely irrelevant to modern Java applications on modern JVMs:

  • Since Java 7, the string pool is no longer a separate heap region.
  • Since Java 8, string space optimization (de-duplication) is performed more efficiently by the GC itself; see https://openjdk.java.net/jeps/192

Calling String.intern was always a rather dubious optimization because it is rarely possible for an application to accurately predict the lifetime of string objects. The downside of interning a string was / is that the string pool indexes use memory, and make more work for the garbage collector.

Upvotes: 8

JunChen
JunChen

Reputation: 41

I think it depends on the methodCall() string .

Upvotes: 0

Related Questions