Argument passing in java is one of the most important topic to cover, Here I am going to elaborate that what happens when different types (primitive or objects) are passed into a method in JAVA. Generally, in any programming language there are only two ways argument passing( parameters passing) to the function:
- Pass – by – Value or call – by – value
- Pass – by – reference or call – by – reference
However, in Java the scenario is a bit different. The first approach is quite similar to other programming language like C/C++ but the second approach makes the JAVA different from others (C/C++). Okay, let’s have a closed at both the ways with examples.
- Pass – by – Value or call – by – value
In this approach the copies of the values of an argument is passed into the formal parameter of the function. Therefore, the changes made to the passed parameter value would not affect to the original copy. In JAVA, when primitive types variable (int, char, float, Boolean…) are passed, they follow the pass – by – value concept. Thus, what occurs to the parameter that receives the argument has no effect outside the method. Look into the below example:
class Test {
void meth(int i, int j) {
i = i * 2;
j = j*3;}
}
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " +
a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " +
a + " " + b);
}
}
The output from this program is shown here:
a and b before call: 15 20
a and b after call: 15 20
As in the above example, the values of a and b are same before and after the calling the meth(). The operation inside meth() did not change the on the original copy of a and b.
- Pass – by – reference or call – by – reference
Leave a Reply