• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Passing a String by reference

 
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
 
Author
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.
 
Wanderer
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.
 
And then we all jump out and yell "surprise! we got you this tiny ad!"
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic