dan-m
12/11/2016 - 3:28 PM

Strings.java

/**
 *  This class illustrates two misconceptions I had about Strings in Java:
 *  - Avoid String concatenation at all costs, use a StringBuffer instead
 *  - Use StringBuffer over StringBuilder
 *
 *  This link helped clear things up a lot: http://www.yoda.arachsys.com/java/strings.html
 *
 *  You can also download cavaj to view decompiled class files to see this in action.
 *
 */
public class Strings {
    public void test(String name) {

        // Source code
        String output = "Hello " + name + ", nice to meet you!";

        // Compiler produces something like this:
        String s = (new StringBuilder()).append("Hello ").append(name).append(", nice to meet you!").toString();

        // Source code
        String test = "daniel " + "moffat";

        // Compiler produces something like this so that concatenation happens at compile time rather than at runtime.
        String s2 = "daniel moffat";
    }
}