Returning Arrays from Method in Java


This Java program defines a function called sortArray() that prompts the user to input an integer limit n, creates an integer array a of size n, and populates the array with n integers inputted by the user. It then sorts the array in ascending order using the Arrays.sort() method and returns the sorted array.

The main method then calls the sortArray() function and stores the returned sorted array in an integer array called arr. Finally, the program uses a for-each loop to iterate over the arr array and print out each element on a new line.

This program demonstrates how to define and call a function in Java that returns an array, and how to sort an array using the Arrays.sort() method

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