Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Call by Value
2.1.
Example
2.2.
Output
2.3.
Explanation
3.
Call by Reference
3.1.
Example
3.2.
Output
3.3.
Explanation
4.
Conclusion
5.
FAQs
6.
Key Takeaways
Last Updated: Apr 28, 2024

Call by Value and Call by Reference in Java

Author Saksham Gupta
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Functions are often the favorite topic of interviewers when it comes to technical interviews. More or less, the questions are theoretically based, and one’s concept around functions should be on tips. But you don’t have to worry about any of it. Ninjas are here for you, and today we will be going to learn one of the most frequently asked questions in this topic, i.e., about Call by value and Call by reference.

Recommended topic- Iteration Statements in JavaDuck Number in Java

Call by Value

The values of actual parameters are copied to the function's formal parameters in this parameter passing mechanism, and the two types of parameters are stored in different memory locations. As a result, any changes made inside functions are not reflected in the caller's actual arguments. Let's understand this better by the example.

Example

class Tester{
   public static void main(String[] args){
      int first = 6;
      int second = 9;
      System.out.println("Before function call, first = " + first + " and second = " + second);
      /* Function will be called*/
      Function(first, second);
      System.out.println("After function call , first = " + first + " and second is " + second);
   }
   public static void Function(int first, int second) {
      System.out.println("Before Function calling the values are (Inside), first = " + first + " second = " + second);
      int temp = first;
      first = second;
      second = temp;
      System.out.println("After operations in function (Inside), first = " + first + " second = " + second);
   }
}

Output

Before function call, first = 6 and second = 9
Before Function calling the values are (Inside), first = 6 second = 9
After operations in function (Inside), first = 9 second = 6
After function call , first = 6 and second is 9

Explanation

Now let's understand each line of the above output.

First, we can see that before the function call, values of variables ‘first’ and ‘second’ will get printed, i.e., 6 and 9.

Second, When we go inside the function, we print the values of ‘first’ and ‘second’. Now we have not made any changes here, so the output would still be the same, i.e., 6 and 9.

Now we are swapping values of ‘first’ and ‘second,’ and then we are printing; thus, the output would be 9 and 6.

Now we have made changes in the copy variables that were created for the function ‘Function’ thus the original values of ‘first’ and ‘second’ will remain unchanged and our output would be 6 and 9.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Call by Reference

Now in the Call by reference method, both the actual and formal parameters correspond to the identical locations. Thus, any changes performed inside the function are reflected in the caller's actual parameters. Only call by value is used in Java while passing reference variables as well. It makes a duplicate of the references and provides them to the methods as useful. Creating a copy of a reference is harmless because it points to the same object's address. However, if a new item is added to the reference list, it will not be reflected. Let's understand this better by the example.

Example

class Testing {
   public static void main(String[] args) {
      Helper first = new Helper(6);
      Helper second = new Helper(9);
      System.out.println("Before function call, first = " + first.variable + " and second = " + second.variable);
   
      /* Function called */
      Function(first, second);
      System.out.println("After function call , first = " + first.variable + " and second is " + second.variable);
     
   }
   public static void Function(Helper first, Helper second) {
      System.out.println("Before Function calling the values are (Inside), first = " + first.variable + " second = " + second.variable);
 
      Helper temp = new Helper(first.variable);
      first.variable = second.variable;
      second.variable = temp.variable;
      System.out.println("After operations in function (Inside), first = " + first.variable + " second = " + second.variable);
   }
}
class Helper {
   public int variable;
   public Helper(int variable){ this.variable = variable;}
}

Output

Before function call, first = 6 and second = 9
Before Function calling the values are (Inside), first = 6 second = 9
After operations in function (Inside), first = 9 second = 6
After function call , first = 9 and second is 6


You can also find the output of this java compiler code here.

Explanation

Now let's understand each line of the above output.

First, we can see that before the function call, values of variables ‘first’ and ‘second’ will get printed, i.e., 6 and 9.

Second, When we go inside the function, we print the values of ‘first’ and ‘second.’ Now we have not made any changes here, so the output would still be the same, i.e., 6 and 9.

Now we are swapping values of ‘first’ and ‘second,’ and then we are printing; thus, the output would be 9 and 6.

Here comes the major difference. After we have exited from function ‘Helper’, we again print values of ‘first’ and ‘second,’ Here, we see the output is 9 and 6 instead of 6 and 9. This is because in call by reference, the values get updated in original variables instead of creating their copy, So once we have swapped the values of ‘first’ and ‘second’ inside the ‘Helper’ function, values in original variables will also get changed.

Conclusion

It's evident from the output that when we used the Call by Value method, values in original variables remained the same, whereas in the Call by Reference method, values in original variables also got affected.

                                                           Source: source

FAQs

  1. Why is Java a platform-independent language?
    Java is platform-independent since it doesn't rely upon a platform. Henceforth, Java is a platform-independent language. In Java, programs are gathered into byte code, which is platform-independent. Any machine to execute the byte code needs the Java Virtual Machine.
     
  2. Why is Java not a purely object-oriented language?
    Java is not a fully object-oriented language as it supports primitive data types like int, byte, long, short, etc., which are not objects. Hence these data types like int, float, double, etc., are not object-oriented. That's why Java is not 100% object-oriented.
     
  3. What is the use of the Java util package?
    It provides the classes necessary to create an applet that communicates with its applet context. It contains all the classes for building user interfaces and painting graphics and images.
     
  4. Why do we use import Java util.*?
    It means importing all the classes and interfaces within java.util package and making them available within the current class or interface. This is shorthand wild card annotation for importing all classes within a particular package.
     
  5. Is there any other Data Structures and Algorithms content in Coding Ninjas Studio?
    Yes, Coding Ninjas Studio allows you to practice coding and answer frequently asked interview questions. The more we practice, the more likely we are to acquire a job at our dream company.

Key Takeaways

In this article, we have extensively discussed the Call by Value and Call by reference methodWe hope that this blog has helped you enhance your knowledge of Call by Value and Call by reference methods, and if you would like to learn more, check out our articles on Library. Do upvote our blog to help other ninjas grow. Happy Coding!

Explore more:

Previous article
Method Hiding in Java
Next article
Collections swap() method in Java with Examples
Live masterclass