Java - Array as Parameter

Introduction

You can pass an array as a parameter to a method or a constructor.

The array must be assignment compatible to the formal parameter type.

Example

The processSalary() method has two parameters:id is an array of int, salary is an array of double

public static void processSalary(int[] id, double[] salary) {
...
}

setValue() method has two parameters: id is int, aka is an array of String

public static void setValue(int id, String[] aka) {
...
}

The printStates() method has one parameter: stateNames is an array of String

public static void printStates(String[] stateNames) {
...
}

The following code accepts an int array and returns the comma-separated values enclosed in brackets [].

public class Main {
  public static String arrayToString(int[] source) {
    if (source == null) {
      return null;
    }

    // Use StringBuilder to improve performance
    StringBuilder result = new StringBuilder("[");

    for (int i = 0; i < source.length; i++) {
      if (i == source.length - 1) {
        result.append(source[i]);
      } else {
        result.append(source[i] + ",");
      }
    }

    result.append("]");
    return result.toString();
  }

  public static void main(String[] args) {

    int[] ids = { 10, 15, 19 };
    String str = arrayToString(ids); // Pass ids int array to arrayToString() method
    System.out.println(str);
  }
}

Related Topics

Exercise