Table of contents
1.
Introduction
2.
What is an Array in Java?
3.
Why Return an Array?
4.
How do you return an array from a method?
5.
Syntax
6.
Returning a One-dimensional Array
7.
Returning a Multi-dimensional Array
8.
Best Practices When Returning Arrays
9.
Common Mistakes and How to Avoid Them
9.1.
1. Returning null instead of an empty array
9.2.
2. Modifying the returned array
9.3.
3. Failing to initialize the array properly:
9.4.
4. Ignoring array bounds
9.5.
5. Not handling exceptions
10.
Real-Life Example
11.
Frequently Asked Questions
11.1.
Can I return arrays of different data types from a method?
11.2.
Is it possible to return an array of arrays (multi-dimensional array) from a method?
11.3.
What happens if I try to access an array element outside its bounds?
12.
Conclusion
Last Updated: Nov 9, 2024
Easy

How to Return an Array in Java?

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Arrays are one of the most important data structures in Java, and they allow you to store and work with collections of elements of the same data type. They provide a structured way to organize and access data efficiently. However, there may be cases where you need to return an array from a method, which allows the data to be used outside the method's scope. 

By returning an array, you can pass multiple values back to the code, which is called the method, which enables more flexible and modular programming techniques. Returning arrays is very useful when you need to perform computations or manipulations within a method and make the results available to other parts of your program. 

How to Return an Array in Java

In this article, we'll discuss how to return arrays from methods in Java, talking about both one-dimensional & multi-dimensional arrays. Apart from this, we'll also discuss best practices and common mistakes to avoid when you are working with arrays.

What is an Array in Java?

An array in Java is a fixed-size data structure that stores elements of the same data type in a contiguous memory block. It provides a way to organize and store multiple values under a single variable name. Each element in an array is assigned a unique index, starting from 0, which allows you to access and manipulate individual elements efficiently.

In Java, arrays are objects and are created using the "new" keyword followed by the data type and the size of the array. For example:

int[] numbers = new int[5];


This creates an integer array named "numbers" with a size of 5, meaning it can store 5 integer values.

Arrays in Java have the following characteristics:

  • Fixed-size: Once an array is created, its size cannot be changed.
     
  • Homogeneous: All elements in an array must be of the same data type.
     
  • Zero-based indexing: The first element in an array has an index of 0, and the last element has an index of (size - 1).
     
  • Random access: Elements in an array can be accessed directly using their index, allowing for fast retrieval and modification.
     

Note: Arrays are commonly used in Java to store and manipulate collections of related data, like a list of numbers, names, or objects. They provide a simple and efficient way to work with multiple values of the same type.

Why Return an Array?

Returning an array from a method in Java offers several benefits and is useful in many different scenarios. Let’s look at some reasons why you might want to return an array:

1. Multiple return values: When you need to return multiple values from a method, an array provides a convenient way to package and return those values together. Instead of returning a single value, you can return an array containing multiple elements.
 

2. Computed results: If a method performs computations or operations that generate multiple results, returning an array allows you to pass all the results back to the calling code. This is particularly useful when the number of results is unknown in advance or can vary based on the input.
 

3. Data encapsulation: By returning an array, you can encapsulate related data within a single entity. This promotes better organization and makes it easier to pass around and manipulate the data as a whole.
 

4. Efficiency: Returning an array can be more efficient than returning individual values one by one. It reduces the number of method calls and data transfers, especially when dealing with large amounts of data.
 

5. Flexibility: Arrays provide flexibility regarding the number and type of elements they can store. Depending on your needs, you can return arrays of different data types, such as integers, strings, or even objects.
 

6. Further processing: Returning an array allows the calling code to perform additional operations or transformations on the returned data. It gives the flexibility to manipulate, analyze, or display the data as needed.

How do you return an array from a method?

To return an array from a method in Java, you need to specify the return type of the method as an array and use the return statement to send the array back to the calling code. Let’s see how you can return an array from a method:

1. Declare the method with the appropriate return type:

When declaring the method, specify the return type as an array of the desired data type. For example, if you want to return an array of integers, the return type would be `int[]`.

   public int[] getNumbers() {
       // Method body
   }


2. Create and populate the array:

Inside the method, create an array of the desired size and populate it with the necessary elements. You can either create a new array or use an existing one.

   public int[] getNumbers() {
       int[] numbers = new int[5];
       // Populate the array
       numbers[0] = 1;
       numbers[1] = 2;
       // ...
   }


3. Return the array:

Use the `return` statement followed by the name of the array to return it from the method.

   public int[] getNumbers() {
       int[] numbers = new int[5];
       // Populate the array
       numbers[0] = 1;
       numbers[1] = 2;
       // ...
       return numbers;
   }


4. Call the method and store the returned array:

When calling the method, assign the returned array to a variable of the appropriate type to store and use it in the calling code.

   int[] result = getNumbers();
   // Use the returned array
   for (int num : result) {
       System.out.println(num);
   }


If you follow these steps, you can effectively return an array from a method in Java. The method creates and populates the array, and the calling code receives the array and can use it as needed.


It's important to note that when returning an array, you are returning a reference to the array object, not a copy of the array. Any modifications made to the returned array will affect the original array in the method.


Also, make sure to properly initialize and populate the array before returning it to avoid returning null or an array with default values.


Note: Returning an array from a method allows you to pass multiple values back to the calling code, allowing for more flexible data handling and manipulation.

Syntax

When returning an array from a method in Java, you need to follow a specific syntax to declare the method's return type and specify the array being returned. 

The syntax for returning an array from a method is:

public <data-type>[] methodName() {
    // Method body
    // Create and populate the array
    return arrayName;
}


In this syntax: 

1. `public`: This is an access modifier that specifies the visibility of the method. It means the method can be accessed from anywhere in the program. You can use other access modifiers like `private` or `protected` based on your requirements.
 

2. `<data-type>[]`: This specifies the return type of the method as an array. Replace `<data-type>` with the actual data type of the elements in the array, such as `int[]`, `String[]`, or `Object[]`.
 

3. `methodName`: This is the name of the method. Choose a meaningful name that describes the purpose or functionality of the method.
 

4. `()`: The parentheses are used to declare any parameters the method accepts. If the method doesn't take any parameters, the parentheses remain empty.
 

5. `{...}`: The curly braces define the body of the method, where you write the code to create, populate, and return the array.
 

6. `return arrayName;`: This statement returns the array from the method. Replace `arrayName` with the actual name of the array variable you want to return.

For example : 

public int[] getEvenNumbers(int count) {
    int[] evenNumbers = new int[count];
    for (int i = 0; i < count; i++) {
        evenNumbers[i] = i * 2;
    }
    return evenNumbers;
}


In this example, the `getEvenNumbers` method takes an integer parameter `count` and returns an array of integers. The method creates an array of size `count` and populates it with even numbers. Finally, it returns the `evenNumbers` array using the `return` statement.

To call this method and retrieve the returned array, you would use the following code:

int[] result = getEvenNumbers(5);


This assigns the returned array to the `result` variable, which can then be used in the calling code.

Returning a One-dimensional Array

Returning a one-dimensional array from a method in Java is very easy. You simply need to create the array, populate it with values, and return it using the return statement. 

Let's discuss an example that shows returning a one-dimensional array of integers:

public int[] getNumbers() {
    int[] numbers = {1, 2, 3, 4, 5};
    return numbers;
}


In this example, the `getNumbers` method creates an integer array called `numbers` and initializes it with the values `{1, 2, 3, 4, 5}`. The method then returns the `numbers` array using the `return` statement.

To call this method and retrieve the returned array, you can use the following code:

int[] result = getNumbers();

 

The returned array is assigned to the `result` variable, which can be used to access and manipulate the array elements.

You can also create and populate the array dynamically based on certain conditions or input parameters. 

Let’s take an example that returns an array of strings based on a given size:

public String[] getNames(int size) {
    String[] names = new String[size];
    for (int i = 0; i < size; i++) {
        names[i] = "Name " + (i + 1);
    }
    return names;
}


In this example, the `getNames` method takes an integer parameter `size` that determines the size of the array. It creates a string array called `names` with the specified size and populates it with string values in the format "Name 1", "Name 2", and so on. Finally, it returns the `names` array.

To call this method and retrieve the returned array, you can use the following code:

String[] names = getNames(3);


This will create an array of size 3 with the values `{"Name 1", "Name 2", "Name 3"}` and assign it to the `names` variable.

Note: Returning a one-dimensional array allows you to pass multiple values of the same type back to the calling code in a structured manner. It provides a convenient way to return a collection of related data from a method.

Returning a Multi-dimensional Array

Java allows you to return multi-dimensional arrays from methods in addition to one-dimensional arrays. Multi-dimensional arrays contain other arrays as elements, forming a grid-like structure. The most common type of multi-dimensional array is a two-dimensional array, which is an array of arrays.

To return a multi-dimensional array from a method, you need to specify the return type as an array of arrays and create the appropriate structure within the method. 

For example : 

public int[][] getMatrix(int rows, int columns) {
    int[][] matrix = new int[rows][columns];
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            matrix[i][j] = i * columns + j + 1;
        }
    }
    return matrix;
}


In this example, the `getMatrix` method takes two integer parameters: `rows` and `columns`. It creates a two-dimensional integer array called `matrix` with the specified number of rows and columns using the `new int[rows][columns]` syntax.
 

The method then populates the `matrix` array using nested loops. It assigns values to each element of the matrix based on a specific pattern (in this case, `i * columns + j + 1`). You can modify the values according to your requirements.
 

Finally, the method returns the `matrix` array using the `return` statement.
 

To call this method and retrieve the returned multi-dimensional array, you can use the following code:

int[][] result = getMatrix(3, 4);

 

This will create a 3x4 matrix and assign it to the `result` variable. The matrix will have the following values:

[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]


You can access individual elements of the returned multi-dimensional array using the row and column indices. For example, `result[1][2]` would retrieve the value 7 from the matrix.

Returning a multidimensional array allows you to pass a grid-like structure of data from a method back to the calling code. It provides a way to work efficiently with tabular or matrix data.

Remember that when using a multi-dimensional array, you return a reference to the array object, just like with one-dimensional arrays. Any modifications made to the returned array will affect the original array in the method.


Note: Returning multi-dimensional arrays can be helpful in many situations, like working with matrices, representing game boards, or storing tabular data. It provides a structured way to organize and manipulate complex data sets within methods and return them to the calling code for further processing.

Best Practices When Returning Arrays

When you are returning arrays from methods in Java, there are many best practices you need to keep in mind to ensure code clarity, maintainability, and efficiency. Some main best practices that you can follow are:

1. Use meaningful method names: Choose method names that clearly indicate the purpose or content of the array being returned. This helps improve code readability and makes it easier for other developers to understand the intent of the method.
 

2. Specify the return type explicitly: Always specify the return type of the method explicitly as an array. This makes it clear to anyone reading the code that the method returns an array and helps with code comprehension.
 

3. Ensure proper array initialization: Before returning an array, ensure it is properly initialized. If you create a new array within the method, always ensure that it is initialized with the appropriate size and default values (if applicable).
 

4. Avoid returning null arrays: Instead of returning a null array, consider returning an empty array or throwing an exception if the array cannot be created or populated. Returning null can lead to null pointer exceptions if not handled properly by the calling code.
 

5. Document the array's purpose and structure: Use comments or Javadoc to document the purpose, structure, and any constraints of the array being returned. This helps other developers understand how to use and interpret the returned array correctly.
 

6. Consider immutability: If the returned array is not intended to be modified by the calling code, consider returning an immutable array or a defensive copy of the array. This prevents unintended modifications to the original array and maintains data integrity.
 

7. Handle exceptions gracefully: If the method encounters any exceptions while creating or populating the array, handle them gracefully. Either catch and handle the exceptions within the method or throw them with appropriate error messages to the calling code.
 

8. Use appropriate array sizes: When creating arrays, consider the expected size based on the input parameters or requirements. Avoid creating unnecessarily large arrays that can consume excessive memory.
 

9. Follow naming conventions: Adhere to the Java naming conventions when naming methods and variables related to arrays. Use meaningful and descriptive names that follow the camelCase convention for variables and methods.
 

10. Test the method thoroughly: Write unit tests to verify the method's behavior that returns an array. Test different scenarios, edge cases, and input variations to ensure the method returns the expected array correctly.

Common Mistakes and How to Avoid Them

When you are working with arrays and returning them from methods in Java, developers often make a few common mistakes. You need to be aware of these mistakes and know how to avoid them, which can help you write more reliable and error-free code. Let's discuss some common mistakes and their solutions:

1. Returning null instead of an empty array

Mistake: Returning null when an array cannot be created or populated.

Solution: Instead of returning null, return an empty array of the appropriate type. This avoids null pointer exceptions and makes the code more predictable.

Example:

   public int[] getNumbers() {
       // Incorrect: returning null
       // return null;
       
       // Correct: returning an empty array
       return new int[0];
   }

2. Modifying the returned array

Mistake: Modifying the array after it has been returned from the method.

Solution: If the returned array is not intended to be modified, consider returning an immutable array or creating a defensive copy of the array before returning it. This prevents unintended modifications to the original array.

Example:

   public int[] getNumbers() {
       int[] numbers = {1, 2, 3};
       // Incorrect: modifying the array after returning
       // numbers[0] = 10;
       
       // Correct: returning a defensive copy
       return numbers.clone();
   }

3. Failing to initialize the array properly:

Mistake: Returning an array without initializing it or with incorrect default values.

Solution: Always ensure that the array is properly initialized before returning it. If necessary, specify the appropriate size and default values.

Example:

   public int[] getNumbers(int size) {
       // Incorrect: array not initialized
       // int[] numbers;
       
       // Correct: initializing the array with the specified size
       int[] numbers = new int[size];
       // Initialize elements if needed
       return numbers;
   }
   ```

4. Ignoring array bounds

Mistake: Accessing array elements outside the valid range, leading to ArrayIndexOutOfBoundsException.

Solution: Always check the array bounds and ensure that index values are within the valid range before accessing elements.

Example:

   public int getElement(int[] array, int index) {
       // Incorrect: accessing element without checking bounds
       // return array[index];
       
       // Correct: checking array bounds before accessing element
       if (index >= 0 && index < array.length) {
           return array[index];
       } else {
           // Handle out-of-bounds index appropriately
           throw new IndexOutOfBoundsException("Invalid index: " + index);
       }
   }

5. Not handling exceptions

Mistake: Not catching or handling exceptions that may occur when creating or manipulating arrays.

Solution: Use try-catch blocks to catch and handle exceptions carefully. Provide appropriate error messages or throw exceptions with meaningful information.

Example:

   public int[] divideNumbers(int[] numbers, int divisor) {
       int[] result = new int[numbers.length];
       for (int i = 0; i < numbers.length; i++) {
           try {
               result[i] = numbers[i] / divisor;
           } catch (ArithmeticException e) {
               // Handle division by zero appropriately
               throw new IllegalArgumentException("Division by zero occurred at index " + i);
           }
       }
       return result;
   } 

Real-Life Example

Suppose you are developing a weather application that retrieves temperature data for a given city over a week. You have a method called `getTemperatures` that takes a city name as input and returns an array of temperatures for that city.

For example : 

public double[] getTemperatures(String city) {
    // Simulating temperature data retrieval from an API or database
    double[] temperatures = new double[7];
    if (city.equalsIgnoreCase("Delhi")) {
        temperatures[0] = 22.5;
        temperatures[1] = 24.3;
        temperatures[2] = 23.8;
        temperatures[3] = 25.1;
        temperatures[4] = 26.7;
        temperatures[5] = 25.9;
        temperatures[6] = 23.2;
    } else if (city.equalsIgnoreCase("Mumbai")) {
        temperatures[0] = 18.2;
        temperatures[1] = 17.9;
        temperatures[2] = 19.5;
        temperatures[3] = 20.3;
        temperatures[4] = 21.1;
        temperatures[5] = 19.8;
        temperatures[6] = 18.7;
    } else {
        // Handle case when city is not found
        return new double[0];
    }
    return temperatures;
}


In this example, the `getTemperatures` method takes a `city` parameter and returns an array of `double` values representing the temperatures for that city over a week.

Inside the method, we simulate retrieving temperature data from an API or database based on the city name. In this case, we have hardcoded the temperature values for two cities: New York and London. If the city is found, the method populates the `temperatures` array with the corresponding values.

If the city is not found, the method returns an empty array using `new double[0]` to indicate that no temperature data is available for that city.

Let’s see an example of how you can use this method in your weather application:

public class WeatherApp {
    public static void main(String[] args) {
        String city = "New York";
        double[] temperatures = getTemperatures(city);
        
        if (temperatures.length > 0) {
            System.out.println("Temperature data for " + city + ":");
            for (int i = 0; i < temperatures.length; i++) {
                System.out.println("Day " + (i + 1) + ": " + temperatures[i] + " degrees C");
            }
        } else {
            System.out.println("No temperature data available for " + city);
        }
    }
    
    // Method to retrieve temperature data for a city
    public static double[] getTemperatures(String city) {
        // Here, we simulate retrieving temperature data based on the city name
        // For demonstration, let's assume we return predefined values for New York
        if (city.equals("New York")) {
            return new double[] { 21.5, 23.7, 19.6, 22.0, 24.5 }; // Example temperatures in degrees C
        }
        return new double[0]; // Return an empty array if no data is available for the city
    }
}


In the `main` method of the `WeatherApp` class, we specify the city for which we want to retrieve temperature data. We call the `getTemperatures` method, passing the city name as an argument, and store the returned array in the `temperatures` variable.


We then check the length of the `temperatures` array. If it is greater than 0, it means temperature data is available for the specified city. We proceed to print the temperature values for each day using a loop. If the length is 0, it means no temperature data is available, and we print a corresponding message.


Note: This real-life example shows how returning arrays from methods can be useful when you need to retrieve and process multiple related values, like temperature data for a given city. By encapsulating the data retrieval logic within a method and returning an array, you can provide a clean and reusable interface for accessing and manipulating the data in your application.

Frequently Asked Questions

Can I return arrays of different data types from a method?

Yes, you can return arrays of any valid data type from a method, such as int[], String[], or even custom object arrays.

Is it possible to return an array of arrays (multi-dimensional array) from a method?

Yes, you can return multi-dimensional arrays from methods by specifying the return type as an array of arrays, such as int[][] or String[][].

What happens if I try to access an array element outside its bounds?

Accessing an array element outside its valid range will throw an ArrayIndexOutOfBoundsException. Always ensure that the index is within the array's bounds before accessing elements.

Conclusion

In this article, we discussed the concept of returning arrays from methods in Java. We learned how to declare methods with array return types, create & populate arrays within methods, and return them using the return statement. We also explained best practices to follow, like using meaningful names, ensuring proper initialization, and handling exceptions. Finally, we covered common mistakes to avoid, like returning null arrays or modifying returned arrays and seeing a real world example.

You can also check out our other blogs on Code360.

Live masterclass