title: What are the benefits of using identical String literals instead of a final variable?
body: <p>I've come across a class that includes multiple uses of a string literal, "foo".</p>
  
  <p>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?</p>
  
  <p>For example (although obviously not a real word usage):</p>
  
  <pre><code>private static final String FINAL_STRING = "foo";
  
  public void stringPrinter(){
      for(int i=0;i&lt;10;i++){
          System.out.println(FINAL_STRING);
      }
  }
  </code></pre>
  
  <p>Versus:</p>
  
  <pre><code>public void stringPrinter(){
      for(int i=0;i&lt;10;i++){
          System.out.println("foo");
      }
  }
  </code></pre>
  
  <p>Which is preferable and why (assuming the string value will remain constant)?</p>
  
  <p>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)?</p>
  
  <p>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:</p>
  
  <pre><code>public void stringPrinter(){
      for(int i=0;i&lt;5;i++){
          System.out.println("foo"); // first occurence
          System.out.println("foo"); // second occurence
      }
  }
  </code></pre>