Friday, August 17, 2007

Java VS C++ : parameter passing

Parameter Passing : Pass-By-Value & Pass-By-Reference.

Parameter passing is something people who moved from C/C++ to Java (or the other way around) get confused.

Let's just explain it with few examples.

-------------------------------------

void main () {
int myAge = 10;
string myName = getName (myAge);
exit (0);
}

string getName (int age) {
age++;
return "My Name";
}

-------------------------------------


What is the value of myAge after getName(myAge) gets executed?
in C --> 10
in C++ --> 10
in Java --> 10


In all 3 languages above, the parameter that is of a primitive type is always being passed by value. What it means is that if getName() function is defined like the one above, the parameter value outside getName() function will never be changed even if the user manipulates the parameter value (e.g. age++) in getName() function.

Then, how about this case?

-------------------------------------

void main() {
Car myCar = new myCar ("Ferrari");
int price = getPrice (myCar);
exit (0);
}

int getPrice (Car aCar) {
aCar.setName("Hyundai");
return 10000;
}

-------------------------------------

What will be returned if myCar.getName() gets called, after getPrice(myCar) gets executed?
in C --> ERROR! there is no class in C. :-)
in C++ --> still a Ferrari.
in Java --> Hyundai!!!!! (Where the hell is my Ferrari?!?!)


This part is the critical difference between Java and C++ when passing parameters to a function.

In Java, if non-primitive data types are passed as a parameter, reference to the data will be passed, ALWAYS! In other words, if manipulation on the parameter is done inside the function, it will be reflected outside the function as well.

To be more precise, Java never holds a object itself like in C++. Instead, it always holds a reference to an object. Also, Java always passes parameters by value, and the parameter being passed to a function is a reference value. oooh, this is not quite so easy to understand, by the way. :-(

Probably many C/C++ programmers will wonder why the name has been changed to Hyundai, or many Java programmers will wonder why the name has not been changed to Hyundai, if the same code was run in C++.

4 comments:

Abhishek Agarwal said...

Good and insightful, implementation wise. A good article to help beginners choose between the two can be found here.
http://mytechrant.com/?p=6

Shounak Gujarathi said...

Thanks man! This was a very good explanation. :)

Shounak Gujarathi said...

Thanks man! This was a very good explanation. :)

Sports education worldwide said...

Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
appvn app