Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

java - Why new keyword not needed for String

I am new in java.

In java, String is a class.But we do not have to use new keyword to create an object of class String where as new is used for creating objects for other classes.

I have heard about Wrapper classes like Integer,Double which are similar to this. But String is not Wrapper,isn't it?

Actually what is happening when i use

     String message = "Hai";

?? How it is different from

String message = new String("Hai");

Here is message a reference variable or something else?? Are there other classes which do not require new to create object ??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With the following line you are not creating a new String object in the heap but reusing a string literal (if already available):

String message = "Hai";

"Hai" is a string literal in the string literal pool. Since, strings are immutable, they are reusable so they are pooled in the string literal pool by the JVM. And this is the recommended way, because you are reusing it.

But, with the following you are actually creating a new object (in the heap):

String message = new String("Hai");

new String("Hai") is a new String object. In this case, even if the literal "Hai" was already in the string literal pool, a new object is created. This is not recommended because chances are that you might end with more than one String objects with the same value.

Also see this post: Questions about Java's String pool

Are there other classes which do not require new to create object ??

Actually, you can not create any object in Java without using the keyword new.

e.g.

Integer i = 1;

Does, not mean that the Integer object is created without using new. It's just not required for us to use the new keyword explicitly. But under the hood, if the Integer object with value 1 does not already exist in cache (Integer objects are cached by JVM), new keyword will be used to create it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...