Pass an integer by reference in Java

Java 8Object Oriented ProgrammingProgramming

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]);
raja
Published on 13-Nov-2018 09:14:09
Advertisements