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 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


Mary Robert

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");
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
Carl Trusiak

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

Please refer to the following for the discussion
I agree. Here's the link:
subject: strings
It's not a secret anymore!