Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it wise to declare a String as final if I use it many times?

I have a method repeatedMethod like this:

public static void repeatedMethod() {
    // something else
    anotherMethod("myString");
    // something else
}

public static void anotherMethod(String str) {
    //something that doesn't change the value of str
}

and I call the repeatedMethod many times.

I would like to ask if it is wise to declare myString as static final outside that method like this:

public static final String s = "myString";

public void repeatedMethod() {
    anotherMethod(s);
}

I think that when I do anotherMethod("myString"), a new instance of String is created. And since I do that many times, many instances of String are created.

Therefore, it might be better to create only one instance of String outside the repeatedMethod and use only that one every time.

like image 690
mimo31 Avatar asked Sep 15 '25 14:09

mimo31


2 Answers

What you are doing is right but for the wrong reason.

When you do anotherMethod("myString"), no new instance of String is actually going to be created: it might reuse a String from the String constant pool (refer to this question).

However, factoring common String values as constants (i.e. as private static final) is a good practice: if that constant ever needs to change, you only need to change it in one place of the source code (for example, if tomorrow, "myString" needs to become "myString2", you only have one modification to make)

like image 138
Tunaki Avatar answered Sep 17 '25 04:09

Tunaki


String literals of the same text are identical, there won't be excessive object creation as you fear.

But it's good to put that string literal in a static final variable (a constant) with a descriptive name that documents the purpose of that string. It's generally a recommended practice to extract string literals to constants with good names.

This is especially true when the same string literal appears in more than one place in the code (a "magic string"), in which case it's strongly recommended to extract to a constant.

like image 20
janos Avatar answered Sep 17 '25 03:09

janos