Friday, August 11, 2017

Argument Passing


There is only call by value in java, not call by reference. If we call a method passing a value, it is known as call by value. The changes being done in the called method, is not affected in the calling method.

Example
Object as Argument
class CallByValue1
{
int data=50;
void change(CallByValue1 op)
{
op.data=op.data+100;//changes will be in the instance variable 
}
public static void main(String args[])
{
 CallByValue1 op=new CallByValue1();
 System.out.println("before change "+op.data);
 op.change(op);//passing object
 System.out.println("after change "+op.data);
 }
}

Example

Value As an Argument

class CallbyValue
{
int data=50;
void change(int data)
{
data=data+100;//changes will be in the local variable only
//System.out.println("local change change"+data);
}
public static void main(String args[])
{
CallbyValue op =new CallbyValue();
System.out.println("before change"+op.data);
op.change(500);
System.out.println("after change"+op.data);
}
}

1 comment:

  1. good,post output screens also for each program by taking screen shot and pasting link here of that screen

    ReplyDelete