wood burning stoves*
The moose likes Beginning Java and the fly likes Passing a String by reference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Passing a String by reference" Watch "Passing a String by reference" New topic
Author

Passing a String by reference

Kelly Harris
Greenhorn

Joined: Mar 27, 2002
Posts: 22
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

Joined: Oct 06, 2002
Posts: 201
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.


Author and Instructor, my book
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
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.


"I'm not back." - Bill Harding, Twister
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Passing a String by reference