| by Arround The Web | No comments

How to Call by Reference in Java

In Java, there are two types of function parameters: The Actual parameter and the Formal parameter. Actual parameters are passed during the function call in another function, whereas formal parameters are the parameters added at the function definition.

In functions, there are two ways to pass an argument or parameters: Call by value and Call by reference. The purpose of this article is to focus on how to call by reference in Java.

How to Call by Reference in Java?

When a function or a method is called in Java, call by reference is the term that refers to a parameter. This method’s core feature is that we use it to refer to the address of a variable. As a result, any change in the variable’s address will be reflected whenever the function that uses it is called or invoked.

Let’s try some examples with the help of the specified method.

Example 1

In this example, first, we will create a method named “add()” by passing two integer type parameters, “x” and “y”. This method will output the sum of the given numbers. Also, the parameters of this method are called the formal parameters:

static int add(int x,int y)
  {
   return x+y;
  }

 
In the main() method, we call the add() method by passing the parameters that refer to the address of the formal parameters. Here, “a” and “b” are the reference parameters for variables “x” and “y”:

public static void main(String[] args) {
    int a=15;
       int b=83;
    System.out.println("The sum of numbers a and b: " + add(a,b));
}

 

The given output indicates that the added parameters are successfully accessed and utilized:

Example 2

In this example, we have two methods: “ref()” and “main()”. The ref() method will add the value of the specified parameters and then multiply it by “3”:


In the main() method, the third line calls the ref() method by passing arguments “a” and “b” that refers to the address of the formal parameters “x” and “y”:

public static void main(String[] args) {
         int a=15;
         int b=83;
         ref(a,b);  
}

 

Output


We compiled all the instructions related to calling by reference in Java.

Conclusion

In Java, you can call the method by passing an argument as a reference in actual parameters. Invoking a method by using call by reference means the argument refers to the variable’s address. Whenever a function is called, the added changes will also reflect the variable. In this article, we have discussed the method for calling by reference in Java.

Share Button

Source: linuxhint.com

Leave a Reply