There is only call by value possible in java, not call by reference.If we call a method passing a value, it is known as call by value.
Example of call by value :
In case of call by value original value is not changed. Let's see a example of it:
class Test{
int num=10;
void modify(int num){
num=num+20; //changes will be in the local variable only
}
public static void main(String []args){
Test t=new Test();
System.out.println("modify value is: "+t.num);
t.modify(40);
System.out.println("modify value is: "+t.num);
}
}
Output:before modify value is:10
after modify value is :60
Another Example of call by value :
In case of call by reference original value is changed if we made changes in the called method. If we pass object in place of any primitive value, original value will be changed. In this example we are passing object as a value. Let's take a simple example:
class Test{
int num=100;
void modify(Student st){
st.num=st.num+100; //changes will be in the instance variable
}
public static void main(String []args){
Test t =new Test();
System.out.println("before modify value is: "+t.num);
t.change(t); //passing object
System.out.println("after modify value is: "+t.num);
}
}
Output: before modify value is:100
after modify value is :200
No comments:
Post a Comment