In
programming language we can call methods either by passing variables value or
variable addresses. Calling a method by passing variable values is called pass by value and calling a method by
passing variable address is called pass
by address and there is no concept called pass by reference as per language designers.
Reference
data type parameters, such as objects, are also passed into methods by value.
This means, that when the method returns, the passed-in reference still refers
the same object as before.
Example –
public class
Method1 {
int x;
int y;
void
abc(Method1 e)
{
System.out.println(e);
e=new Method1();
System.out.println(e);
}
public static void
main(String[] args) {
Method1 m1 = new
Method1();
Method1 m2 = new
Method1();
System.out.println("m2: "+m2);
m1.abc(m2);
System.out.println("m2: "+m2);
}
}
Output –
m2: method.Method1@15db9742
method.Method1@15db9742
method.Method1@6d06d69c
In the above program we have
assigned new object to parameter variable. After that method execution, In main
method m2 is still pointing to its own object. Since argument variable value is
not changed when we change parameter value, this point proves that passing
objects as argument also come under pass by value. However, the values of the
object’s non-static variables can be changed in this method and those object
modifications are effected to passed-in reference variable, because both
passed-in reference variable and method point parameter point to the same
object.
No comments:
Post a Comment