Java – string instantiation and StringBuffer instantiation
•
Java
I can't figure out 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
Only valid when created with new
Why can string be instantiated directly, but StringBuffer needs new operator Someone can explain my main reason
Solution
All objects need to be instantiated with new Primitives can only be instantiated from text (int i = 0;)
The only exceptions are:
>String, allowing special initialization structures:
String s = "abc"; //can be instantiated from a literal,like primitives
> null instantiation:Object o = null;
It is defined in Java language specification #3.10:
Note: arrays also have a special initialization mode, but this is not text:
int[][] a = { { 00,01 },{ 10,11 } };
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码