In C, when you pass by reference, you pass the *address* of the object.
And you dereference that *address* if you want to change the object.
Consider this C code, which passes the *address* of a string (character
array).
main()
{
char *astring = "main";
fill(astring);
printf("%s\n", string);
}
fill(char *astring)
{
astring = "test";
}
The output would be "main" and not "test". Does this surprise anyone?
Why does the equivalent Java code surprise you? In both cases, a
*reference* to *the string* is passed. In both cases, the *string*
itself is not modified. In both cases, the local *copy of the
reference* is modified in the subroutine, and this does not change the
value of *the original reference* in the main routine.
If you want to change the value of the variable in main(), you must pass
*a reference* to that variable. In C, this is easy, you pass the
address of the variable:
main()
{
char *astring = "main";
fill (&astring);
printf("%s\n", string);
}
fill(char **astring)
{
*astring = "next";
}
This prints "next". The equivalent Java code is more complex, because
Java doesn't allow you to take the address of a variable. An
array-based solution has been presented. I'll present a class-based
solution:
public class Test {
private static class StringRef {
private String the_string;
public StringRef(String a_string) { the_string = a_string; }
public void setString(String a_string) { the_string = a_string; }
public String getString() { return the_string; }
}
public static void main(String[] args) {
String my_string = "main";
StringRef my_ref = new StringRef(my_string);
fill(my_ref);
my_string = my_ref.getString();
System.out.println(my_string);
}
public static void fill(StringRef a_ref)
{
a_ref.setString("test");
}
}
This code will print "test". The subroutine fill() receives a reference
to the *StringRef* object. Since it has this reference, it can call
methods of the StringRef that will modify the contents of the StringRef
object.
The question that started this thread used String and Integer as the
example objects. Both of these classes have NO methods that modify the
value of the object. So even though a reference to the String or
Integer is passed to the subroutine, there is NO WAY that the subroutine
can change the contents of the String or Integer. And the only
modifications a subroutine can make to its parameters is to change the
contents of the objects to which those parameters *refer*.
Hope this helps.
=Spencer
To change your membership options, refer to:
http://www.sys-con.com/java/list.cfm