StringBuilder sb = "asd";
In Java, this statement is obviously wrong. IDEs like eclipse will tell you that :
cannot convert from String to StringBuilder
However, a String
object could be initialized by =
operator.
I'd like to know some reasons related with the memory allocation.
Converting a String to StringBuilder The append() method of the StringBuilder class accepts a String value and adds it to the current object. To convert a String value to StringBuilder object just append it using the append() method.
StringBuilder is used to represent a mutable string of characters. Mutable means the string which can be changed. So String objects are immutable but StringBuilder is the mutable string type.
StringBuilder will only create a new string when toString() is called on it. Until then, it keeps an char[] array of all the elements added to it. Any operation you perform, like insert or reverse is performed on that array.
Because StringBuilder
is an Object and it needs to be constructed. You're getting the error because String is not a StringBuilder
.
String is a special, it's designed to be between primitive and class1. You can assign a string literal directly into a String variable, instead of calling the constructor to create a String instance.
1interesting topic:
The designers of Java decided to retain primitive types in an object-oriented language, instead of making everything an object, so as to improve the performance of the language. Primitives are stored in the call stack, which require less storage spaces and are cheaper to manipulate. On the other hand, objects are stored in the program heap, which require complex memory management and more storage spaces.
For performance reason, Java's String is designed to be in between a primitive and a class.
More reading:
"xxx"
is defined as a String literal by the specification of the language* and is a String object. So 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 a String is not a StringBuilder...
*Quote from the JLS: "A string literal is always of type String
"
StringBuilder is an object not a wrapper.
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