File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String Question" Watch "String Question" New topic

String Question

Kay Liew
Ranch Hand

Joined: Dec 26, 2003
Posts: 112
Question from MindQ's

11. The statement ...

String s = "Hello" + "Java";

yields the same value for s as ...

String s = "Hello";
String s2= "Java";
s.concat( s2 );

Answer is false ?!? Could that be a mistake or have I mis-understood the question ?

Unity can only be manifested by the Binary. Unity itself and the idea of Unity are already two.
osman cinar eren
Ranch Hand

Joined: Jan 25, 2005
Posts: 78
It really is false. that is about the String class in Java. String objects are IMMUTABLE. that is:

s.concat(s2) creates a new object whose value is equal to s+s2, but as this new object is not referenced by any variable, it is unreachable. On the other hand, the original object referenced by 's' remains unchanged.

You should read on the concept of String.

hope this helps.

meena latha
Ranch Hand

Joined: Jan 24, 2005
Posts: 219
s i do agree....
If u dont create a object reference to the string the content will be lost.
But with StringBuffer it doesnt happens like that.

StringBuffer s= new StringBuffer("welcome");

Welcome here.
Kay Liew
Ranch Hand

Joined: Dec 26, 2003
Posts: 112
I understand that String is immutable. But the question as is the "value" the same and not are they the same or "==",

To me, values mean the final print out which in this case both resulted HelloJava.

Ok, i guess the problem is how one define "value". In this case, I thought it is asking about the final printout and not asking about "==" or equal() .
Steven Bell
Ranch Hand

Joined: Dec 29, 2004
Posts: 1071
The final value in the two would not be the same.
You missed one thing in your code.

Kay Liew
Ranch Hand

Joined: Dec 26, 2003
Posts: 112

If you do not alter my original code.

What is the printout of One and Two ? Now isn't that the "value" the same ?
Steven Bell
Ranch Hand

Joined: Dec 29, 2004
Posts: 1071
But the question was 'yields the same value for s'

when you do
you are not printing the value of s, but the value returned by the concat method.
ankur rathi
Ranch Hand

Joined: Oct 11, 2004
Posts: 3830
In a very simplle manner :

"Hi ".concat("How are you");

will return ( what you are thinking is right ) :
Hi How are you

but you don't have any reference for this object , so this is immutable .

s.concat(s1) ; // don't think that result of this will be refereed by s ( it happens in StringBuffer , not in String ) .
[ January 27, 2005: Message edited by: rathi ji ]
I agree. Here's the link:
subject: String Question
It's not a secret anymore!