Java | Argument Passing

05 min read

Argument Passing:

Java uses call-by-value to pass all arguments; however, the effect differs between whether a primitive type or a reference type is passed.

1. When a primitive type is passed to a method, it is passed by value. Thus a copy of the argument is made & what occurs to the parameter that receives the argument has no effect outside the method.

class sample
{
void modify(int i, int j)
{
i * = 2;
j / = 2;
System.out.println("i = " + i + " j = " + j); ---> 10 5
}
}
class samplemain
{
public static void main(String[ ] args)
{
sample s = new sample( );
int a = 5, b = 10;
System.out.println("a = " + a + " b = " + b); ---> 5 10
s.modify(a,b);System.out.println("a = " + a + " b = " + b); ---> 5 10
}
}

 

2. When an object is passed to a method, it works similar to call-by-reference. This is because, when you pass the reference to a method, a copy of that reference is taken and passed. Thus the parameter that receives it will refer to the same object as that referred to by the argument. Thus changes made inside the method affects the actual object.

class sample
{
int a, b;
static void modify(sample s)
{
s.a *= 2;
s.b /= 2;
}
}
class samplemain
{
public static void main(String[ ] args)
sample s1 = new sample( );
s1.a = 5;
s1.b= 10;
System.out.println("a = " + s1 .a + " b = " + s1 .b); ---> 5 10
sample.modify(s1);  
System.out.println("a = " + s1.a + " b = " + s1.b); -> 10 5
}
}

As 's' also refers to the same object, the changes made to 'a' and `b' variables referred to by 's' ( in the modify() method) are directly done in the object. s1 1000 (address of object).

 

Point to ponder while passing reference variables to a method: changes made in the objects referred to by the reference variables, within the called method are reflected even in the calling method and hence changes made to the objects are permanent. On the other hand, changes made to the reference variables themselves are not permanent and so not reflected in the calling  method.

class Sample
{
int a,b;
static void modify(Sample s1 , Sample s2)
{
s1.a = s 1.a+5;
s1.b+=10;
Sample temp;
temp=s 1;
s1=s2;
s2=temp;
System.out.println(s 1 .a+ " " + s1.b);
System.out.println(s2.a+ " " + s2.b);
}
public static void main(String[] args)
{
Sample s1=new Sample();
s1.a= 10;
s1 .b=20;
Sample s2=new Sample();
s2.a=100;
s2.b=200;
modify(s1 ,s2);
System.out.println(s1.a+ " "+s 1.b);
System.out.println(s2.a+ " "+s2.b);
}
}
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error