Pass by Value and Pass by Reference
Example of pass by value
Example of pass by reference
Example of pass by value
class X
{
void modify(int x,int y)
{
x++;
y++;
System.out.println("Value of x is "+x+" and y is "+y);
}
}
class Test
{
public static void main(String args[])
{
X obj=new X();
int a=100,b=200;
obj.modify(a,b);
System.out.println("After Modification Values
are "+a+" "+b);
}
}
Output
Value of x is 101 and y is 201 After Modification Values are 100 200
Example of pass by reference
Example of pass by reference
class X
{
int a,b;
X()
{
a=100;
b=200;
System.out.println("Inside X Default Constructor ");
}
void modify(X obj)
{
obj.a++;
obj.b++;
System.out.println("Value of a is "+obj.a+"
and b is "+obj.b);
}
}
class Test
{
public static void main(String args[]){X temp=new X();
{
temp.modify(temp);
System.out.println("Value of a and b inside
main "+temp.a+temp.b);
}
}
Output
Inside X Default Constructor Value of a is 101 and b is 201 Value of a and b inside main 101201


