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")?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With