Primitive data types in Java is passed by value where as objects are always passed by reference.
class CallByReference
{
int a, b;
CallByReference(int x, int y)
{
a = x;
b = y;
}
void met1(CallByReference m)
{
m.a =m.a * 2;
m.b =m.b / 2;
}
public static void main(String[] args)
{
CallByReference p1 = new CallByReference(10, 20);
System.out.println(p1.a+" "+p1.b);
p1.met1(p1);
System.out.println(p1.a+" "+p1.b);
p1.met1(p1);
System.out.println(p1.a+" "+p1.b);
}
}
OUTPUT :
10 20
20 10
40 5
Call by value :
class CallByValue
{
int met1(int a)
{
return ++a;
}
public static void main(String[] args)
{
int i = 10;
CallByValue p = new CallByValue();
int j = p.met1(i);
System.out.println(i);
System.out.println(j);
}
}