How to return an array from a method in Java?

Java 8Object Oriented ProgrammingProgramming

We can return an array in Java from a method in Java. Here we have a method createArray() from which we create an array dynamically by taking values from the user and return the created array.

Example

 Live Demo

import java.util.Arrays;
import java.util.Scanner;

public class ReturningAnArray {
   public int[] createArray() {
      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();
      }
      return myArray;
   }

   public static void main(String args[]) {
      ReturningAnArray obj = new ReturningAnArray();
      int arr[] = obj.createArray();
      System.out.println("Array created is :: "+Arrays.toString(arr));
   }
}

Output

Enter the size of the array that is to be created::
5
Enter the elements of the array ::
23
47
46
58
10
Array created is :: [23, 47, 46, 58, 10]
raja
Published on 09-Jan-2018 05:09:49
Advertisements