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.

有帮助吗?

解决方案

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.

This works

String sb = "asd";

because you have a reference to a String literal being assigned to a variable reference. i.e. the types are the same.

You can't do this implicitly convert types or change an object with assignment in Java.

Object o = "asd";

Works because the String is an Object.

String is not only a class but anything inside "" is a JVM String and String object refers to that string.
So String str="hello" works.

But StringBuilder and other thousands of objects are not as special as String so they do not get initiialized likewise.

In java the String is a special type of class u can define object for String like

String s = "xyz";

or

String s = new String("XYZ");

But StringBuilde**r is just like a **normal class and when u have to create a object for it you should use new keyword(Construct the object). HTH

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top