Skip to content

Returning array from methods

In Java, methods can return arrays just like any other data type. Since arrays are objects in Java, a method can return a reference to the array. This feature allows methods to process data and provide results in the form of an array, which is useful for handling multiple values simultaneously.


Syntax for Returning an Array

  1. Define the method to return the array’s data type (e.g., int[], double[], String[]).
  2. Use the return statement to return the array reference.

returnType[] methodName(parameters) {

    // Logic to create or manipulate an array

    return arrayReference;

}


Examples

1. Returning an Array from a Method

In this example, a method generates and returns an array of integers.

public class Main {

    // Method to generate an array of numbers

    public static int[] generateNumbers(int size) {

        int[] numbers = new int[size];

        for (int i = 0; i < size; i++) {

            numbers[i] = i + 1; // Populate with consecutive numbers

        }

        return numbers;

    }

    public static void main(String[] args) {

        int[] result = generateNumbers(5);

        System.out.println(“Returned Array:”);

        for (int num : result) {

            System.out.print(num + ” “);

        }

    }

}

Output:

Returned Array:

1 2 3 4 5


2. Returning a Processed Array

This example demonstrates how a method can return a modified version of an input array.

public class Main {

    // Method to double the values in an array

    public static int[] doubleValues(int[] inputArray) {

        int[] result = new int[inputArray.length];

        for (int i = 0; i < inputArray.length; i++) {

            result[i] = inputArray[i] * 2;

        }

        return result;

    }

    public static void main(String[] args) {

        int[] original = {1, 2, 3, 4, 5};

        int[] doubled = doubleValues(original);

        System.out.println(“Original Array:”);

        for (int num : original) {

            System.out.print(num + ” “);

        }

        System.out.println(“\nDoubled Array:”);

        for (int num : doubled) {

            System.out.print(num + ” “);

        }

    }

}

Output:

Original Array:

1 2 3 4 5

Doubled Array:

2 4 6 8 10


3. Returning a Multidimensional Array

A method can also return a multidimensional array.

public class Main {

    // Method to generate a multiplication table

    public static int[][] generateMultiplicationTable(int size) {

        int[][] table = new int[size][size];

        for (int i = 0; i < size; i++) {

            for (int j = 0; j < size; j++) {

                table[i][j] = (i + 1) * (j + 1);

            }

        }

        return table;

    }

    public static void main(String[] args) {

        int[][] table = generateMultiplicationTable(5);

        System.out.println(“Multiplication Table:”);

        for (int i = 0; i < table.length; i++) {

            for (int j = 0; j < table[i].length; j++) {

                System.out.print(table[i][j] + “\t”);

            }

            System.out.println();

        }

    }

}

Output:

Multiplication Table:

1        2        3        4        5       

2        4        6        8        10     

3        6        9        12      15     

4        8        12      16      20     

5        10      15      20      25


4. Returning an Array of Strings

A method can return an array of objects, such as strings.

public class Main {

    // Method to return names

    public static String[] getNames() {

        return new String[]{“Alice”, “Bob”, “Charlie”, “Diana”};

    }

    public static void main(String[] args) {

        String[] names = getNames();

        System.out.println(“Names:”);

        for (String name : names) {

            System.out.println(name);

        }

    }

}

Output:

Names:

Alice

Bob

Charlie

Diana


5. Returning a Subset of an Array

A method can return a portion of an array.

import java.util.Arrays;

public class Main {

    // Method to extract a subarray

    public static int[] getSubArray(int[] inputArray, int start, int end) {

        return Arrays.copyOfRange(inputArray, start, end);

    }

    public static void main(String[] args) {

        int[] original = {10, 20, 30, 40, 50};

        int[] subArray = getSubArray(original, 1, 4);

        System.out.println(“Subarray:”);

        for (int num : subArray) {

            System.out.print(num + ” “);

        }

    }

}

Output:

Subarray:

20 30 40


Best Practices

  1. Avoid Returning Null: Always return an empty array (new int[0]) instead of null to avoid NullPointerException.

return new int[0];

  • Immutable Arrays: If the returned array should not be modified, consider using Arrays.copyOf() to return a copy instead of the original array.
  • Validation: Validate parameters before creating or manipulating arrays to prevent errors like ArrayIndexOutOfBoundsException.
  • Efficient Design: For large data sets, consider returning immutable views or lists to avoid unnecessary copying.

Conclusion

Returning arrays from methods in Java is a powerful feature that enables clean and efficient programming. Whether working with single or multidimensional arrays, this feature provides flexibility for data manipulation and results aggregation. Understanding array-returning techniques ensures efficient coding practices and better resource management.