How to pass Arrays to Methods in Java

So lets first see what are methods in java. Then we will see a program on How to pass Arrays to Methods in Java.

A method contains a block of code which we need to run at the time of execution. The method is mostly used when we have to run a block of statements repeatedly. It gets executed when we call them using some parameters. They may or may not have a return value. A method is always defined inside a class and can be called anywhere. It can be called outside the class with the help of an object.

A method can be public or private to that class. Public means it can be called anywhere in the program but in case of private, we can call only in that particular class.

Syntax:

class MyExample {
  public void myMethodPublic() {
    // statements that are to be executed when called
  }
}

Program: How to pass Arrays to Methods in Java

import java.util.Scanner;

public class passArray {
   public void printIntArray(int [] array) {
           for(int i=0; i<array.length; i++ ) {
         System.out.println("Elements of Integer array:"+array[i]);
      }
   }
       public void printDoubleArray(double array[]) {
           for(int i=0; i<array.length; i++ ) {
         System.out.println("Elements of double array:"+array[i]);
      }
   
   }
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array 1:");
      int size1 = sc.nextInt();
      int[] arrayEx1 = new int[size1];
      System.out.println("Enter the elements of the array1:");
      
      
      for(int i=0; i<arrayEx1.length; i++) {
         arrayEx1[i] = sc.nextInt();
      }

      System.out.println("Enter the size of the array 2:");
      int size2 = sc.nextInt();
      double[] arrayEx2 = new double[size2];
      System.out.println("Enter the elements of the array2 (in double):");



      for(int i=0; i<arrayEx2.length; i++) {
         arrayEx2[i] = sc.nextInt();
      }
      passArray method = new passArray();
      method.printIntArray(arrayEx1);
      method.printDoubleArray(arrayEx2);
   }
}

 

Explanation:

In this code, we have initialized a class name passArray which consists of two methods printIntArray and printDoubleArray. This method will print the value stored in the array.

In the main function, we have initialized two arrays as per user-defined size one in integer datatype and other in double datatype. The values will be stored as per the data type in the array.

Now we have initialized an object to pass the array to the two methods which are defined in class passArray.We pass the array as the parameter to the method and there can be any number of parameters and its datatype.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *