Clicky

Mustafa Veysi Soyvural: 2009

Friday, 27 March 2009

WHICH ONE JAVA DOES SUPPROT? CALL BY REFERENCE or CALL BY VALUE

Many developers know that Java supports "call by references" when a method is invoked. They claim that java only use "call by value" when parameters are primitive types. And what about the truths :) the truth is absolutely different then this myth.

EVERYTHNG IN JAVA PASSED BY VALUE SO JAVA SUPPORTS ONLY "CALL BY VALUE".

C++ also supports both of call by reference and call by value methods. Let's look at an example of C++ code, the below block of code clearly illustrates the differences of these methodologies.



/*
** author: Mustafa Veysi Soyvural
**
*/

#include
using namespace std;

class A {
private:
int a;
public:
A() { a = 0; }
int getA( ) { return a; }
void setA(int _a) { this->a = _a; }
};

//call by value
void funcA( A *a ) {
a = new A();
cout << "Function using Call By Value " << "a: " << a->getA() << endl;
}

//call by reference
void funcA( A &a ) {
A *b = new A();
a = *b;
cout << "Function using Call By Reference " << "a: " << a.getA() << endl;
}

int main() {
A *a = new A();
cout << "Initial value a: " << a->getA() << endl;
a->setA(6);
cout << "After a->setA(6), a: " << a->getA() << endl;
funcA(a);
cout << "After calling funcA( A *a ), a: " << a->getA() << endl;
funcA(*a);
cout << "After calling funcA( A &a ), a: " << a->getA() << endl;
return 0;
}


The output of this code is here:
1. Initial value a: 0
2. After a->setA(6), a: 6
3. Function using Call By Value a: 0
4. After calling funcA( A *a ), a: 6
5. Function using Call By Reference a: 0
6. After calling funcA( A &a ), a: 0


Pay attention to 4th and 6th raws, if you use "call by reference" method you can change the real object. In this example funcA( A &a ) changes the address of a object where it points to heap memory area. But when you use call by value method you can change the value of pointer which is in the stack.

Briefly, you can change the real object only by using call by reference. Otherwise you can change only the obect which has been copied into the stack.

I also want to give an example from Java to show that Java does only supports "Call By Value" method.

public class CallByValue {
public static void funcA( String myStr ) {
myStr = "I am a temp string in funcA :)";
System.out.println(myStr);
}

public static void main(String[] args) {
String s = "Mustafa Soyvural";
System.out.println(s);
funcA(s);
System.out.println(s);
}
}


Here is the output of this program:
Mustafa Soyvural
I am a temp string in funcA :)
Mustafa Soyvural