Monday, June 28, 2004

 

java method parameters

in languages like c,c++ you can have multiple ways of passing method parameters namely
* Pass By Value
* Pass By Reference
* Pass By Pointer

in java you don't have much of choice, except what the language provides you. in simple terms, the primitives in java (int,long,boolean,float,byte,char etc) are passed by value.
meaning no change done to that value inside the method will be reflected outside (at the caller). the objects are a different story. they're passed by value in some sense, while they're passed by reference for many cases.
why the confusion? the java objects are passed by value in the sense that if you change the object itself (by creating a new object and make the parameter point to that) it will not be reflected outside. but its passed by reference in the sense that if you change the state of the object by invoking methods on it then it will be reflected outside.
for example you invoked a method on an object and that method changed some value of attribute (or initialized a attribute object it contains) then that change will be visible to the caller after the method is done. for c/c++ users its equivalent to passing by pointers (you can change the state of the object pointed by the pointer, but not the pointer itself).

let us see some examples

void changeString(String s1, String s2) {
s1 = new String("new1");
s2 += "abc";
}

if you invoke this following way

String s1 = new String("123");
String s2 = new String("456");
changeString(s1,s2) after the invoking the values will still be "123"
and "456". the first is not surprising since it initializes a new pointer,
but later might be surprising. the fact is java's strings are immutable
hence java makes a new pointer "456abc" for string s2 in the method
which will not be reflected outside.

how will you make the string value change reflect outside. make a wrapper.
let us call this StringWrapper. it will look like this

public class StringWrapper {

private String value_;

public StringWrapper() { value_ = null; }

public StringWrapper(String value) { value_ = value; }

public String getValue() { return value_ ; }

public void setValue(String value) { value_ = value; }

}

now you can use this in the method

public void changeString(StringWrapper s1, StringWrapper s2) {

s1 = new StringWrapper("new1");
s2.setValue("abc");
}

on invoking this like following

StringWrapper s1 = new StringWrapper("123");
StringWrapper s2 = new StringWrapper("456");
changeString(s1,s2);

now the value of s1 and s2 after invoking will be "123" and "abc".
first value is not changed (changing of original object not reflected)
while second will be changed (s2 is now set to "abc").



This page is powered by Blogger. Isn't yours?