Passing By-Value & By-Reference

for me there was a very big confusion when I tried to learn java at the beginning. so I will try to clear the situation for anyone who might have some questions about how Java treats with parameters inside its methods.

  • Method parameters as primitive type: the value will be copied into the methods scope and the result won’t affect outside the methods unless you return the result. so it’s by value.
  • Method parameters as class reference: the value will be copied into the methods scope and the result won’t affect outside the methods unless you return the result. so it’s by value.

so it shows, it doesn’t matter whether parameters of the methods are primitive types or class instance, the params will always be copied for methods and outside of the methods don’t have access to its internal changes.

if you want to take affect the by-reference you can use and update the content of the objects using references inside the method. that’s the only way I am using to change whatever I want and make that consistent outside of my methods body.

so since the parameters are immutable, any changes won’t affect outside, so for changing outside variables, the only way is to update and do the change inside the methods using the class variables itself, for example:

public void myChangerMethod(Person p1, Person p2){

// doing anything with p1 nad p2 won’t affect unless you can use these references to

Person p_temp = p1;

p1 = p2;

p2 = p_temp; // these lines won’t change anything outside of this method.

//change their object content itself. something like below:

String name_temp = p1.getName();

p1.setName(P2.getName()); // modifying content

p2.setName(name_temp); // modifying the first content.

}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s