English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Pass an integer by reference in Java

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

Example

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 Result

100

In the above program, a custom method is created that passes an int array.

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

In this method, we perform mathematical operations on the array values.

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

The updated value is then displayed in the main window.

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