Why can't I use String to initialize a StringBuilder?

StringBuilder sb = "asd"; 

In Java, this statement is clearly incorrect. IDEs like eclipse will tell you that:

cannot convert from String to StringBuilder

However, a String object can be initialized with the = operator.

I would like to know some reasons related to memory allocation .

+7
java stringbuilder
source share
6 answers

Because StringBuilder is an Object and needs to be built. You get an error because String is not a StringBuilder .

The string is special; it is intended to be between primitive and class 1 . You can assign a string literal directly to a String variable instead of calling the constructor to create an instance of String.

1 interesting topic :

Java designers decided to save the primitive types in an object-oriented language, instead of making everything an object, therefore, to improve the work of the language. Primitives are stored in the call stack, which require less storage space and are cheaper to manipulate. On the other hand, objects are stored in a heap program that require complex memory management and more storage space.

To improve performance, Java String is designed for primitive and class.

Additional Information:

+10
source share

"xxx" defined as a string literal by the language specification * and is a String object. Therefore, you can write:

 String s = "abc"; //ok we got it Object o = "abc"; //a String is an Object CharSequence cs = "abc"; //a String is also a CharSequence 

But the string is not a StringBuilder ...

* Quote from JLS: "A string literal is always of type String "

+10
source share

StringBuilder is an object that is not a wrapper.

+1
source share

It works

 String sb = "asd"; 

because you have a reference to a string literal that is assigned a reference to a variable. that is, the types are the same.

You cannot do this implicitly converting types or changing an object with a destination in Java.

 Object o = "asd"; 

It works because String is an object.

+1
source share

String is not only a class, but everything inside "" is a JVM String and String object referencing this string.
Therefore String str="hello" works.

But StringBuilder and other thousands of objects are not as special as String , so they also don't get initialized.

0
source share

In java, a string is a special type of class . u can define an object for String as

 String s = "xyz"; 

or

 String s = new String("XYZ"); 

But StringBuilde ** r is like a regular class , and when you need to create an object for it, you have to use the new keyword (Construct the object), NTN

0
source share

All Articles