Khangharoth

May 1, 2006

In Java Methods pass by value and pass by refrence

Filed under: Java — khangharoth @ 7:53 am

While invoking Java methods we pass primitives and Objects .
First we will discuss primitives .In primitives method is always invoked by copy of primitive value so even if method changes its value ,the initial primitive value in calling method remain same.

 public class TestMethodEnvokation {
public static void main(String[] args) {
 int count = 10;
 TestMethodEnvokation object = new TestMethodEnvokation();
 object.doStuff(count);
 System.out.println(count);
}

private void doStuff(int counter) {
 counter = 12;
}
}

In this example 10 will get printed and not 12 as only value of count was passed to the method doStuff.

But in case of objects its the copy of refrence which is passed so effectively passing a refrence to method effectiively create new refrence for the passed object and scope of this refrence is limited to the method only.

  public class TestMethodEnvokation {
public static void main(String[] args) {
 TestMethodEnvokation object = new TestMethodEnvokation();

 Employee emp = new Employee();
 emp.name = "name";
 object.doStuff(emp);
 System.out.println(emp.name);
}

private void doStuff(Employee emplyee) {
 emplyee.name = "name Changed";
}
}

class Employee {
String name = null;
}

In this example the content of passed object gets changed showing method has a refrence of the object.

To Show that passed refrence was copy of refrence and not original one see output of the example below.

 public class TestMethodEnvokation {
public static void main(String[] args) {
 TestMethodEnvokation object = new TestMethodEnvokation();

 Employee emp = new Employee();
 emp.name = "name";
 object.doStuff(emp);
 System.out.println(emp.name);
}

private void doStuff(Employee emplyee) {
 emplyee=null;
}
}

class Employee {
String name = null;
}

Although we have made refrence in method as null still original refrence is unaffected .

Advertisements

2 Comments »

  1. Google is the best search engine

    Comment by John Harris — January 19, 2007 @ 12:33 am | Reply

  2. Hi,

    It is really nicely explained.

    Thanks!

    Comment by guddu — June 12, 2008 @ 10:30 am | Reply


RSS feed for comments on this post. TrackBack URI

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

Blog at WordPress.com.

%d bloggers like this: