call by value in Java:
If a method is to be called by passing a parameter as a value then it is said to be Call by Value. Here the changes made to the passed parameter do not affect the called method.
Example of call by value:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | class CallByValue { void meth(int x, int y) { x = x + 10; y = y - 20; System.out.println("The result after the operation performed:"); System.out.println("a = " + x + "\t b = " + y); } } public class JavaMain { public static void main(String args[]) { CallByValue obj = new CallByValue(); int a =50, b = 100; System.out.println("The value of a and b before the call :"); System.out.println("a = " + a + "\t b = " + b); obj.meth(a, b); System.out.println("The value of a and b after the call : "); System.out.println("a = " + a + "\t b = " + b); } } |
Output:
1 2 3 4 5 | a = 50 b = 100 The result after the operation performed: a = 60 b = 80 The value of a and b after the call : a = 50 b = 100 |
call by reference in Java:
If a method is to be called by passing a parameter (not the value) as a reference then it is said to be Call by Reference. Here the changes are made to the passed parameter effect on the called method.
Example of call by reference:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | class CallByRef { int x, y; CallByRef(int i, int j) { x = i; y = j; } /* pass an object */ void method(CallByRef p) { p.x = p.x + 2; p.y = p.y + 2; } } public class JavaMain { public static void main(String args[]) { CallByRef obj = new CallByRef(10, 20); int x = 10, y = 20; System.out.println("The value of a and b before the call :"); System.out.println("a = " + obj.x + "\t b = " + obj.y); obj.method(obj); System.out.println("The value of a and b after the call : "); System.out.println("a = " + obj.x + "\t b = " + obj.y); } } |
Output:
1 2 3 4 | The value of a and b before the call : a = 10 b = 20 The value of a and b after the call : a = 12 b = 22 |