wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes strings 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 "strings" Watch "strings" New topic
Author

strings

Mary Robert
Greenhorn

Joined: Jan 04, 2001
Posts: 13
hi! every one,
i've a dbt in strings..
In the following code:
public static void main(String args[])
{
String s1 = new String("java");
String s2 = new String("java");
s1 = s1.concat("c");
StringConcat(s2);
System.out.println("s1 is : " + s1);
System.out.println("s2 is : " + s2);
}
public static void StringConcat(String str)
{
str = str.concat("c");
}
when i compile and execute this code, i get the answer's as:
s1 is : javac
s2 is :java
what is the reason for this? please clarify my dbt.
thanking u
mary.
Carl Trusiak
Sheriff

Joined: Jun 13, 2000
Posts: 3340
This is because objects are passed to methods as a copy of it's reference. To understand this fully read Pass by Value Please campfire story.


I Hope This Helps
Carl Trusiak, SCJP2, SCWCD
Tom Tang
Ranch Hand

Joined: Dec 24, 2000
Posts: 133
Hi, Mary:
As Carl said, the reason why s2 remains the same is because you just passed a copy of reference of s2 to the method, so the original s2 reference still points to Java. str is the local varialbe of the method and lost visibility as soon as the method ends. However you can change s2's reference with the following code:

Now, you use the return new String to redefine s2.
Or you can do this to use the method to manipulate s2 directly:

And you have the same output.


Sun Certified Java Programmer
Tom Tang
Ranch Hand

Joined: Dec 24, 2000
Posts: 133
However:

Please refer to the following for the discussion
http://www.javaranch.com/ubb/Forum24/HTML/007081.html
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: strings
 
Similar Threads
Doubt in String class
Can this be a case of deadlock ?And how to determine it output ?
== with Strings is giving a different result
String Pool
code behaving strangely