Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string instantiation vs stringbuffer instantiation

Tags:

java

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.

like image 896
Sejwal Avatar asked Dec 16 '22 20:12

Sejwal


1 Answers

All objects need to be instantiated with new. Only primitives can be instantiated from a literal (int i = 0;).

The only exceptions are:

  • strings, which allow a special initialisation construct:
   String s = "abc"; //can be instantiated from a literal, like primitives
  • null instantiation: Object o = null;

It is defined in the Java Language Specification #3.10:

A literal is the source code representation of a value of a primitive type, the String type, or the null type.

Note: arrays also have a dedicated initialisation patterm , but that's not a literal:

   int[][] a = { { 00, 01 }, { 10, 11 } };
like image 64
assylias Avatar answered Dec 23 '22 15:12

assylias