1

I have some knowledge about string pool in Java. All examples in the network conected with creating variables explicitly. But what will happen if I return hardcoded string from method. Is it use string pool or string will be created again and again for each method call. I can't find any information about this case.

I have such example:

public class TestService {

  @Override
  protected Optional<String> getPayTypeCode() {
      return Optional.of("LDV");
  }
  //...
}

Example with constant:

public class TestService {
  private static final String PAY_CODE = "LDV";

  @Override
  protected Optional<String> getPayTypeCode() {
      return Optional.of(PAY_CODE);
  }
  //...
}

And I am wondering, is my first case use string pool? And which case will work faster?

Yurii Kozachok
  • 615
  • 1
  • 7
  • 21
  • 1
    Possible duplicate of [What is Java String interning?](https://stackoverflow.com/questions/10578984/what-is-java-string-interning) – Michał Ziober Sep 16 '19 at 09:34
  • Both are identical w.r.t. asked feature. Using `private static final Optional PAY_COPE = Optional.of("LOV");` would be a bit "better" - with the disadvantage of a global object needing initialisation (time & space). – Joop Eggen Sep 16 '19 at 09:34

1 Answers1

5

The string pool will be used for all string literals, it doesn't matter if you use it in the method body or to initialize a static final field. Both of those will use the string pool (and return interned string objects).

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • Is better use private constant if it is used only once in class? – Yurii Kozachok Sep 16 '19 at 09:40
  • From a purely technical perspective there is pretty much no difference. This is more a question about code style and readability and opinions differ. If it's only used in a single place and the value is somewhat self-explanatory I'd not define a constant. If the reason for that specific value isn't obvious, then I'd define a constant even if only used ina single place. – Joachim Sauer Sep 16 '19 at 11:21