Returning Arrays from Method in Java


An array is a collection of similar data elements stored at contiguous memory locations. It is the simplest data structure where each data element can be accessed directly by only using its index number. The method returning the array must have the return type as an array of the same data type as that of the array being returned.

Source Code

import java.util.Arrays;
import java.util.Scanner;
 
public class function_array {
 
    public static int[] sortArray() {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter The Limit : ");
        int n = in.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            System.out.println("Enter The Value " + i + " : ");
            a[i] = in.nextInt();
        }
        Arrays.sort(a);
        // returning  array
        return a;
    }
 
    //Returning Arrays from Method
    public static void main(String args[]) {
        int arr[] = sortArray();
        for (int a : arr)
            System.out.println(a);
    }
 
 
}
 

Output

Enter The Limit :
5
Enter The Value 0 :
10
Enter The Value 1 :
11
Enter The Value 2 :
12
Enter The Value 3 :
13
Enter The Value 4 :
14
10
11
12
13
14
To download raw file Click Here

Basic Programs