Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can not use a String to initialize a StringBuilder object?

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.

like image 711
chain ro Avatar asked Jan 16 '14 10:01

chain ro


People also ask

Can you cast string to StringBuilder?

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.

Why did you use StringBuilder instead of string?

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.

Does StringBuilder create new string?

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.


3 Answers

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:

  • JLS
  • Java tutorials
like image 70
Maroun Avatar answered Nov 15 '22 16:11

Maroun


"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"

like image 22
assylias Avatar answered Nov 15 '22 17:11

assylias


StringBuilder is an object not a wrapper.

like image 39
SuRu Avatar answered Nov 15 '22 18:11

SuRu