pass array as parameter java code example

Example 1: java pass array as method parameter

/*
In java, you can create an array like this:
	new int[]{1, 2, 3};
replace `int` with whatever you want
*/

public static void doSomething(int[] list) {
	System.out.println("Something is done."); 
}

public static void main(String[] args) {
  	doSomething(new int[]{1, 2, 3});
}

Example 2: how to put a string in an array parameter java

public class Test {
  public static void main(String[] args) {
    // Declare a constant value for the number of lockers
    final int NUMBER_OF_LOCKER = 100;

    // Create an array to store the status of each array
    // The first student closed all lockers, each lockers[i] is false
    boolean[] lockers = new boolean[NUMBER_OF_LOCKER];

    // Each student changes the lockers
    for (int j = 1; j <= NUMBER_OF_LOCKER; j++) {
      // Student Sj changes every jth locker
      // starting from the lockers[j - 1].
      for (int i = j - 1; i < NUMBER_OF_LOCKER; i += j) {
        lockers[i] = !lockers[i];
      }
    }

    // Find which one is open
    for (int i = 0; i < NUMBER_OF_LOCKER; i++) {
      if (lockers[i])
        System.out.println("Locker " + (i + 1) + " is open");
    }
  }
}

Example 3: java pass new array to method

methodName(new int[]{1, 2, 3}); // Replace int for different types

Example 4: passing array to function java

public int min(int [] array) {
      int min = array[0];
   
      for(int i = 0; i<array.length; i++ ) {
         if(array[i]<min) {
            min = array[i];
         }
      }
      return min;
   }
int minimum = min(myArray)

Tags:

Cpp Example