Listen to this article

We have seen numerous posts on Java this month relating to Classes, methods, Inheritance, Interfaces, Access modifiers, Non-access modifiers , exceptions and more. While many may sound mind boggling at first, constantly working with them makes you a resolute Java professional! 🙂 We still haven’t seen two important concepts and they are of ‘call by value’ and ‘call by reference’.

Let us see them in this post:

Call by value:

We have seen methods in Java. To recap, this is a method in Java:

void add(int a, int b){
   c=a+b;
    
}

The method ‘add’ takes two parameters(‘a’ and ‘b’) and adds them and stores them in another variable called ‘c’. The method does not return any value, so its return value is ‘void’.

In ‘call by value’ a copy of the values is passed and the original values remain unchanged.

Here is a simple program to illustrate this:

 

  1. We print the value of ‘a’ before employing ‘call by value’.
  2. Two values are passed to the method ‘show’. Within the method, the values are added.
  3. When we print it again, we see that the original value is not modified.

Call by reference:

In ‘call by reference’, an object reference is passed as the parameter. When we change the value, the original value is changed as well. Let us see this by means of an example:

 

The line:

c.show(c);

passes the object ‘c’ to the ‘show’ method. When the passed value is changed, the original value changes as well.

‘Call by value’ and ‘Call by reference’ are two important concepts in Java.

To recap:

In ‘call by value’ only the copy is passed as the parameter so the original value does not change

In ‘call by reference’ the object is passed as parameter so the original value will change if modifications are done.

Come back tomorrow for more! 🙂

I’m participating in #BlogchatterA2Z by Blogchatter 

(Visited 43 times, 1 visits today)

Related Posts

2 thoughts on “Useful concepts in Java

Leave a Reply