• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Passing a String by reference

 
Kelly Harris
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a need to be able to set/change a String value in a called method. Does anyone know how to pass a String "by reference" and not "by value"?
example code might be:
public void setValue( String value)
{
value = "I am now set to a value";
}
public static void main(String args[])
{
MainClass test = new MainClass();
String str1 = "";
String str2 = new String("");
test.setValue( str1);
System.out.println( "str1=" + str1);
test.setValue( str2);
System.out.println( "str2=" + str2);
}

I DO NOT want to have a method like:
public String setValue()
{
return "I am now set to a value";
}

Thanks for your help
kelly
 
James Chegwidden
Author
Ranch Hand
Posts: 201
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kelly,
All Objects in Java (like Strings) are pass by reference. However this "pass by reference" is not like other languages- C and C++.
Also, String objects are immutable- which means they physically cannot be changed. If you want to physically change the string then use something like the StringBuffer class.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Different people use different terminology, but since as you note Java-style "pass by reference" is not the same as the "pass by reference" used by programmers of other languages. So we really shouldn't call it that - it just creates confusion. James Gosling takes a more correct approach and says Java passes references by value rather than passes by reference - see here. (Thanks, Roseanne!)
Kelly - aside from using a StringBuffer, another option is to use an instance field:

This works because both getValue() and setValue() refer to the same variable, value. In your original attempts, setValue() only has a local variable called value, which is a copy of a reference to a String object. Changing the value of the local variable has no effect on the String object, or on any outside code which does not have access to the local variable.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic