I am just starting out with Java. But I had a big puzzle when I am in the first chapter.
It says that we have to "initialize" the handle when we are creating one, like String s = "asdf",
And later it says we have create a new object for the String s again, String s = new String("asdf");
I think the String s already has an object (asdf) in the "initialization, but why we still have to re-create it again(if I am understanding it right)?
Hope someone can explain this more to me, in book it is just skipped. Thanks a lot.

3 Years
Discussion Span
Last Post by kenadams

ehm ... you don't "have to", not according to Java anyway, maybe it's a part of the exercise you are reading?

anyway, the following code:

String s = "asdf";
String s = new String("asdf");

would not compile, since you are declaring two variables with an identical name.

maybe the book is merely showing you the two (most basic) ways to initialize a String instance.

Votes + Comments
Yeah, now I kinda figured that out.. But really I didn't realise that the book is trying to show me two different examples for a same case...Maybe I took a leap in picking a Java book for myself XD

This is one of those irrelevant technical questions that interviewers like to ask, but don't ever matter in practice:

String s1 = "asdf";
String s2 = "asdf";

the compiler is smart enough to create just one String object.

String s1 = "asdf";
String s2 = new String("asdf");

the compiler will create two String objects.

Bercause Strings are immutable there is no reason I know of to use the second version.

Votes + Comments
Okayyy, I think your answer just removed my mist. So in the normal case, we would most likely use String s1 ="asdf", right?


Yes, String s1 = "asdf"; is the way to do it. The other form is useless.

But if you look on the web you will find one justification for new String, which is based on taking a small substring from a very large string. That was valid up to Java 1.6.20-ish, but after that the internal implementation of substring was changed to always create a new string. So if you are using any current version of Java the substring justification is no longer valid.


Yeah I was kinda forced to update to Java 7 by Oracle so it works on me. And I also just heard something similar from the other people. String s1 = "asdf" is like pointing s1 to the COMMOM POOL as a Literal, While String s1 = new String("asdf") is to create a new Object for s1. So now it is pretty much clear for me. Thanks very much! :D

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.