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

Create a free website or blog at WordPress.com.