Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - weird static String behavior - new String("xxx") vs "xxx"

public class Test {

    private static final String str1 = new String("en");
    private static Test instance = initInstance();

    private static final String str2 = new String("en");
    private static final String str3 = "en";

    private Test() {
    }

    public static void main(String[] args) {
    }

    private static Test initInstance() {
        instance = new Test();
        System.out.println(str1 + ',' + str2 + ',' + str3);
        return instance;
    }
}

Theoretically with statics everywhere it should result in "en,en,en".

Result: "en,null,en"

Expected: "en,null,null" (since i discovered statics order actually matters)

Could somebody explain this? What is so different about "en" and new String("en")?

like image 865
drag0nius Avatar asked Jul 20 '12 13:07

drag0nius


1 Answers

Yes. At the time you invoke the method, str2 is not yet initialized (fields are initialized in order of declaration) and str3 is a compile-time constant.

Compile-time constants are inlined by the compiler in the class file. new String("..") is not a constant, because it uses a constructor.

String constants are defined by the string literal: "", and they are placed in a string pool in the jvm instance so that they are reused. Contrary to that, using new String(..) creates a new instance, and so should be avoided.

like image 164
Bozho Avatar answered Oct 03 '22 05:10

Bozho