Search code examples
javafinalstring-literals

Does a final String inside a private static method instantiate a new object when invoked?


Does a static final String inside a private static method instantiate a new object when invoked?

private static String Test() {
    final String foo = "string literal";
    return foo;
}

Or does the compiler know there is only a single, string literal, inside the method? Or should I make it a private static final class field? This has the effect of reducing readability by spreading the code around the class.


Solution

  • No, the particular string will be reused from the string literal pool. If it was for example:

    final String foo = new String("string literal");
    

    Then indeed a new one will be created everytime the method is invoked.

    Here's an evidence:

    public static void main(String[] args) throws Exception {
        String s1 = test1();
        String s2 = test1();
        System.out.println(s1 == s2); // true
    
        String s3 = test2();
        String s4 = test2();
        System.out.println(s3 == s4); // false
    }
    
    private static String test1() {
        final String foo = "string literal";
        return foo;
    }
    
    private static String test2() {
        final String foo = new String("string literal");
        return foo;
    }
    

    Note that the final modifier doesn't have any influence in this particular case. It only prohibits the variable from being reassigned.