0

Why it's better to use a string into a static field instead of declaring it every time it's needed?

// Old scenario
Person p = new Person("Charles", "Xavier");
Person p = new Person("Charles", "Doe");
Person p = new Person("Charles", "Johnson");

// New scenario
private static String name = "Charles"

Person p = new Person(name, "Xavier");
Person p = new Person(name, "Doe");
Person p = new Person(name, "Johnson");

I have like a good practice to replace the same String like "Charles" with a static field, but regarding memory use and performance, is it better?

Leandro Maro
  • 325
  • 1
  • 12
  • It would be exactly the same, if you wrote `private static final String name = "Charles";` Unfortunately a mutable variable is not so good, at least make in non-static then. – Joop Eggen Dec 03 '19 at 15:32
  • 2
    It has nothing to do with performance and memory use but with readability and maintainability, etc. They are so called ["magic strings"](https://softwareengineering.stackexchange.com/questions/365339/what-is-wrong-with-magic-strings) – luk2302 Dec 03 '19 at 15:34
  • 1
    Memory-wise, it's actually ever-so-slightly worse to use the variable, because you now permanently consume the space for a `String` reference variable. But that should be absolutely **the very least of your worries**; many other considerations, readability and maintainability high among them, should be foremost in your mind. – Kevin Anderson Dec 03 '19 at 15:46

1 Answers1

3

In terms of JVM is concerned, both are same and both go to the String pool.

However, from a code quality perspective, it's better to define as a constant so that you have a single point to look and change if you have to do that later.

Lal Mohandas
  • 116
  • 5