0

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?

2 Answers2

8

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • 1
    Given the costs associated with `intern()`, it never was an optimization, but only a tool for special semantics. E.g., the runtime implementation for annotations has to parse class file data, construct strings from it, and then use `intern()` to reestablish the compile-time constant semantic of the annotation values. It’s worth noting the a literal is a *source code* construct. When you have `foo() { return "xyz"; }` you have a method using a literal, but when you have `bar() { return foo(); }`, it does not use a literal, but still has exactly the same, indistinguishable result. – Holger Aug 17 '20 at 11:02
0

I think it depends on the methodCall() string .

JunChen
  • 41
  • 1
  • 3