• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

strings

 
Mary Robert
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Tom Tang
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Tom Tang
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
However:

Please refer to the following for the discussion
http://www.javaranch.com/ubb/Forum24/HTML/007081.html
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic