OOPS in JAVA 4
Call-by-value and Call-by-reference
There are two ways to pass an argument to a method.
Call-by-value:
In this approach copy of an argument value is pass to a method. Changes made to the argument value inside the method will have no effect on the arguments.
Call-by-reference:
In this reference of an argument is pass to a method. Any changes made inside the method will affect the agrument value.
NOTE : In Java, when you pass a primitive type to a method it is passed by value whereas when you pass an object of any type to a method it is passed as reference.
Example of call-by-value.
public class Test
{
public void callByValue(int x)
{
x=100;
}
public static void main(String[] args)
{
int x=50;
Test t = new Test();
t.callByValue(x); //function call
System.out.println(x);
}
}
Output : 50
Example of call-by-reference.
public class Test
{
int x=10;
int y=20;
public void callByReference(Test t)
{
t.x=100;
t.y=50;
}
public static void main(String[] args)
{
Test ts = new Test();
System.out.println("Before "+ts.x+" "+ts.y);
ts.callByReference(ts);
System.out.println("After "+ts.x+" "+ts.y);
}
}
Output :
Before 10 20
After 100 50
No comments:
Post a Comment
Hai , Post your comment . (required, Bugs, Errors )