Modifying an Array Parameter Inside a Method - Java Object Oriented Design

Java examples for Object Oriented Design:Method Parameter

Description

Modifying an Array Parameter Inside a Method

Demo Code

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] origNum = {1, 2, 3};
    System.out.println("Before method call:" + Arrays.toString(origNum));
    //from   w  w  w .  ja v a 2  s  .  c om
    // Pass the array to the method
    tryArrayChange(origNum);
    
    System.out.println("After method call:" + Arrays.toString(origNum));
  }

  public static void tryArrayChange(int[] num) {
    System.out.println("Inside method-1:" + Arrays.toString(num));

    // Create and store a new int array in num
    num = new int[]{10, 20};

    System.out.println("Inside method?2:" + Arrays.toString(num));
  }
}

Result


Related Tutorials