Question: I've come across a class that includes multiple uses of a string literal, "foo".

What I'd like to know, is what are the benefits and impact (in terms of object creation, memory usage and speed) of using this approach instead of declaring the String as final and replacing all the literals with the final variable?

For example (although obviously not a real word usage):

```
private static final String FINAL_STRING = "foo";

public void stringPrinter(){
    for(int i=0;i<10;i++){
        System.out.println(FINAL_STRING);
    }
}

```

Versus:

```
public void stringPrinter(){
    for(int i=0;i<10;i++){
        System.out.println("foo");
    }
}

```

Which is preferable and why (assuming the string value will remain constant)?

Would the above (second) example result in 10 String objects being created or would the JVM realise that only a single literal is actually used, and create a single reference. If so, is there any advantage for declaring the String as final (as in the first example)?

If the interpreted code does replace the string literal with a single reference, does that still apply if the same literal occurs in more than one place:

```
public void stringPrinter(){
    for(int i=0;i<5;i++){
        System.out.println("foo"); // first occurence
        System.out.println("foo"); // second occurence
    }
}

```

Answer: 
[From the JLS](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html)  

*Compile-time constants of type String are always "interned" so as to share unique instances, using the method String.intern.*

So, no, there's gonna be only one string object. 

As Mark notes, this is strictly the question of maintainability and not performance.
All String literals are kept in a String cache (this is across all classes)

Using a constant can make the code clearer, give the the string some context and make the code easier to maintain esp if the same string appears in multiple places.