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.
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 ]
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
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
posted
0
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
posted
0
forgot to include the output in my previous example... Here it is: ---- BEFORE s is before update --------AFTER s is before update