How to pass Arrays to Methods in Java?

Java 8Object Oriented ProgrammingProgramming

You can pass arrays to a method just like normal variables. When we pass an array to a method as an argument, actually the address of the array in the memory is passed (reference). Therefore, any changes to this array in the method will affect the array.

Suppose we have two methods min() and max() which accepts an array and these methods calculates the minimum and maximum values of the given array respectively:

Example

 Live Demo

import java.util.Scanner;

public class ArraysToMethod {
   public int max(int [] array) {
      int max = 0;

      for(int i=0; i<array.length; i++ ) {
         if(array[i]>max) {
            max = array[i];
         }
      }
      return max;
   }

   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;
   }

   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array that is to be created::");
      int size = sc.nextInt();
      int[] myArray = new int[size];
      System.out.println("Enter the elements of the array ::");

      for(int i=0; i<size; i++) {
         myArray[i] = sc.nextInt();
      }
      ArraysToMethod m = new ArraysToMethod();
      System.out.println("Maximum value in the array is::"+m.max(myArray));
      System.out.println("Minimum value in the array is::"+m.min(myArray));
   }
}

Output

Enter the size of the array that is to be created ::
5
Enter the elements of the array ::
45
12
48
53
55
Maximum value in the array is ::55
Minimum value in the array is ::12
raja
Published on 09-Jan-2018 05:16:18
Advertisements