GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes Passing 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 string by reference..." Watch "Passing string by reference..." New topic
Author

Passing string by reference...

Vin Man
Greenhorn

Joined: Jun 13, 2001
Posts: 26
Hi,
Can anyone please tell me how to pass a string by reference, as I might have to change the content of the string within the called function. Thanks in advance.
Jamie Robertson
Ranch Hand

Joined: Jul 09, 2001
Posts: 1879

Originally posted by Vin Man:
Hi,
Can anyone please tell me how to pass a string by reference, as I might have to change the content of the string within the called function. Thanks in advance.

Unfortunately, java only allows you to pass by value. Fortunately for you, the value of a String is a copy of its reference. So, you are passing the String reference by value
Jamie
[ May 31, 2002: Message edited by: Jamie Robertson ]
Jamie Robertson
Ranch Hand

Joined: Jul 09, 2001
Posts: 1879

I guess I should have also mentioned that Strings are immutable. Therefore you can't change the contents of the String you passed in to the method. So it won't work as you intended. Are you looking for a way to return more than one changed value from your method?
Jamie
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4474
    
    6

You'd have to pass a reference to a container of some sort, like an array. See this code:
Vin Man
Greenhorn

Joined: Jun 13, 2001
Posts: 26
Junilu,
Thanks for your advice. I followed your example and it worked!
I thought I read somewhere that for anything to be passed by reference, it has to be of some object types. So out of curiosity, I made mine (before changing it to an array of string) to be of type Object, but apparently that was not right. See code and output below. Wonder what is going on there...
private static void zzz(Object strObj){
strObj = new String ("should see this now");
}
public static void main(String[] a)
{
//String[] s = {"before update"};
Object s = new String("before update");
System.out.println("---- BEFORE s is " + (String) s);
zzz( s );
System.out.println("--------AFTER s is " + (String) s);
}
...
Vin Man
Greenhorn

Joined: Jun 13, 2001
Posts: 26
forgot to include the output in my previous example... Here it is:
---- BEFORE s is before update
--------AFTER s is before update
Jamie Robertson
Ranch Hand

Joined: Jul 09, 2001
Posts: 1879

found that this link had a good explanation of your problem.
Jamie
Amir Kamran
Ranch Hand

Joined: Apr 21, 2002
Posts: 48
Hello!
use StringBuffer instead of string it will solve ur problem.
 
GeeCON Prague 2014
 
subject: Passing string by reference...