• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

strings

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
However:

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