Why does Java allow to assign a string literal to a String object?

蓝咒 提交于 2021-02-16 14:57:25

问题


String is a class in java. While declaring and assigning string, it is correct to say String name = "Paul" though to instantiate an object from a java class we do String name = new String(); Taking name as an object, I'm wondering why we can assign a series of characters "Paul" to the object. Under what concept does this one works and how does it?


回答1:


That's because implicitly Strings - "..." are treated as objects as well.

Under the cover JVM looks for similar "objects" in so called String pool and then if it finds it there it returns that object (instead of creating new one) otherwise creates new object and puts it to String pool.

This is for memory efficiency, and "Paul" so new String("Paul") is not the same.

This is possible because as we know, strings are immutable in Java.

You can read more about this behavior search for keyword "string pool".




回答2:


In Java code

"Paul"

is a String literal and

String name

a variable of type String with the name name.

The Java Language Specifications, section 3.10.5 states:

A string literal is always of type String

As 123 is an int literal and int number is a variable of type int with the name number, following both statements are legal, because the type on the left- and righthand side of the assignments match:

int number = 123;
String name = "Paul";


来源:https://stackoverflow.com/questions/16542250/why-does-java-allow-to-assign-a-string-literal-to-a-string-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!