Pass an integer by reference in Java


To pass an integer by reference in Java, try the following code −

Example

 Live Demo

public class Demo {
   public static void display(int[] arr) {
      arr[0] = arr[0] + 50;;
   }
   public static void main(String[] args) {
      int val = 50;
      int[] myArr = { val };
      display(myArr);
      System.out.println(myArr[0]);
   }
}

Output

100

In the above program, a custom method is created, which pass an int array.

int val = 50;
int[] myArr = { val };
display(myArr);

In the method, we have performed mathematical operation on the value of array.

public static void display(int[] arr) {
   arr[0] = arr[0] + 50;;
}

The updated value is then displayed in the main.

System.out.println(myArr[0]);

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

756 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements