This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String question" Watch "String question" New topic
Author

String question

Nikhil Bansal
Greenhorn

Joined: Mar 21, 2006
Posts: 21
Consider the foll String operation

1.
String str1 = "Test"
String str2 = "";

System.out.println(str1 == (str1+str2));

2.
String str1 = "Test"
String str2 = "";

System.out.println(str1 == str1.concat(str2));

Plz provide the answer with explainations.

Regards

Nikhil Bansal
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17249
    
    6

"NikhilBansal"

Please click on the My Profile link above and in the Display Name field, please just add a space between your first and last names to meet the naming policy. Thanks.

True, False. String pool for the first one, second that concat() method returns a brand new String object.

Mark


Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
Higgledy Smith
Ranch Hand

Joined: Mar 07, 2006
Posts: 192
this is a great question. Here is my guess.

System.out.println(str1 == (str1+str2));
This compares the instance reference value to the str1+str2 objects' value. This is false.

System.out.println(str1 == str1.concat(str2));
I know that a new String object gets assigned the values of (str1+str2) and the instance refence str1 get reassigned to this new String object.
I cannot explain why this evalutes the two string values.
Higgledy Smith
Ranch Hand

Joined: Mar 07, 2006
Posts: 192
Mark: Can you add more detail to you explaination?
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Mark]: True, False. String pool for the first one, second that concat() method returns a brand new String object.

Ummm... no and no.

Those of you guessing and asking for explanations: has anyone tried actually compiling and running this code, to see what happens? You may well still have questions afterwards, but you ought to at least be able to find out what the correct answer is, right?


"I'm not back." - Bill Harding, Twister
Asha Pathik
Ranch Hand

Joined: Feb 08, 2006
Posts: 143
Hi,

According to me the answer would be False and True and explanation for that is

1)str1==(str1+str2)
here the compiler is creating an annonymous string object for (str1+str2) and comparing the address of that with the "str1". Since the addresses are diff. u will get false.

2)str1==str1.concat(str2)
here compiler is just compairing the address of str1 with itself because concat operation is called on str1 object. If either we call the concat operation on some other string object or store its result and then compare, we will get diff. result.

Regards,
Asha


SCJP 1.5
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
I agree with Jim. It's easy to find out what the code will do or whether there will be a syntax error by compiling and/or running.

Consider this code.



This prints false true.

The reason the first one is false is that even though "Test" and "" are in the String pool, str1+str2 is not interned so a new object is created.

The reason the second one is true is that according to the API docs for String, if the length of the argument to concat is 0, then the String that called the method is returned.

Notice what happens if you modify the code.



This prints true true.
[ March 21, 2006: Message edited by: Keith Lynn ]
Higgledy Smith
Ranch Hand

Joined: Mar 07, 2006
Posts: 192
Thanks for the explaination. Praise be to Jim Yingst.
Nikhil Bansal
Greenhorn

Joined: Mar 21, 2006
Posts: 21
Thanks a lot Keith.Your answers have cleared my doubts.

Regards

Nikhil Bansal
Narendra Babu
Greenhorn

Joined: Mar 22, 2006
Posts: 1
== looks for reference only.
in this case str1+str2 means its adding both str1 and str2 and reffering to different memory location.in case of concat it is refferin the same memory location.
Shaliey Gowtham
Ranch Hand

Joined: Mar 20, 2006
Posts: 104
JLS says that the s.concat(s1) returns the s(same refrence) when agrument s1.length==0;
Changchun Wang
Ranch Hand

Joined: Feb 15, 2006
Posts: 83
the operator �+� that has been overloaded for String objects. Overloading means that it has been given an extra meaning when used with a particular class. (The �+� and �+=� for String are the only operators that are overloaded in Java.)
that is say The �+� and �+=� are methods(special). what are the difference between them and other String's methods ?
from above I see some differene
String s1="java";
String s2="";
System.out.println(s1==s1+s2);
System.out.println(s1==s1.concat(s2));
why the method concat return the old String(s1)
but the special method (+ oparator) do not retrn the old String?
anyone can explain it?
thanks !
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
The concat method returns the same thing simply because that's the way the method is designed. The + operator when used between Strings will produce another String object.
Changchun Wang
Ranch Hand

Joined: Feb 15, 2006
Posts: 83
also there are more methods from String class
replace()
subString()
trim()
toLowerCase() toUpperCase()
are just like concat() will return old Strings if no changes happen?

more problem:
s="java";
System.out.println(s="java"+"");
why o/p true
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
My guess is that since "java" and "" are in the String pool, there concatenation is automatically interned.

Notice that this also prints true.



But this prints false.

Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
I checked in the JLS. It states that String concatenation will result in a new object being created if one of the operands is a non constant. constant Strings are String literals.
Valentin Jacquemin
Ranch Hand

Joined: Feb 15, 2006
Posts: 35
Originally posted by Keith Lynn:
I checked in the JLS. It states that String concatenation will result in a new object being created if one of the operands is a non constant. constant Strings are String literals.


So the result will be true false no?
Raghavan Muthu
Ranch Hand

Joined: Apr 20, 2006
Posts: 3344

hey buddies [esp changchun wang],
answer for the qn why concat() method of String class returns the same String if the length of the string being concatenated is 0 => as another buddy said, the way its designed.
For those of you who dint see the code, here it is:


Hope its permitted to give the code implementation. If its not permitted, kindly let me know.

I have a doubt in the post of keith Lynn. You have given two different set of codes.


---------------------------------------------------------------


In the first one, as the string literals being compared are already present in the String Pool, they are interned automatically?
If its true, the second one deals with every single string objects and they are not automatically interned, the concatenation of those objects will yield a brand new String object? thereby it gives false!?

Clarify me if i m wrong in my understanding please.

Thanks a lot,
Raghavan alias Saravanan M.


Everything has got its own deadline including one's EGO!
[CodeBarn] [Java Concepts-easily] [Corey's articles] [SCJP-SUN] [Servlet Examples] [Java Beginners FAQ] [Sun-Java Tutorials] [Java Coding Guidelines]
Amirr Rafique
Ranch Hand

Joined: Nov 14, 2005
Posts: 324
Hi all
Why below code retun ture.

Please explain

Thanks


"Know where to find the solution and how to use it - that's the secret of success."
Mohammed Yousuff
Ranch Hand

Joined: Apr 18, 2006
Posts: 45
Hi, in the above question, the reference of string str1 == (str1+str2) will return false because str1+str2 will have new Object which will have new Reference in the heap. but when we do the same with String.concat(), it returns True because concat method check the length of the String argument and If the length of the argument string is 0, then this String object is returned. So here no new String is created ... Bye


Regards<br /> <br />Mohammed Yousuff M N <br /> <br />Try NOT to Become a man of SUCCESS, BUT Try to Become a man of VALUE..
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String question
 
Similar Threads
String handling
comparing Strings
Referencing to another object
String comparison
intern method