I am not able to figure out that if
String ab = "hello"; //straight initialization
String ab_1 = new String ("hello_1"); //initializing using new
both work, but
StringBuffer bfr = new StringBuffer("hi"); //works only with new
works only if created with new.
Why it is that String can be instantiated directly but StringBuffer needs new operator. Can someone explain me the main reason please.
All objects need to be instantiated with
new. Only primitives can be instantiated from a literal (int i = 0;).The only exceptions are:
Object o = null;It is defined in the Java Language Specification #3.10:
Note: arrays also have a dedicated initialisation patterm , but that’s not a literal: