Is string pool works in case of returning values from method?

Yurii Kozachok :

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?

Joachim Sauer :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=307640&siteId=1