Hello,
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.

Recommended Answers

All 4 Replies

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.

commented: 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 +0

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.

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

Postscript:

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.