Skip to content
Related Articles

Related Articles

Improve Article

How to Return an Array in Java?

  • Last Updated : 01 Oct, 2021

An array is a data structure that consists of a group of elements of the same data type such that each element of the array can be identified by a single array index or key. The elements of the array are stored in a way that the address of any of the elements can be calculated using the location of the first index of the array using a simple mathematical relation. Arrays in Java are different in implementation and usage when compared to that in C/C++ although they have many similarities as well. Here we will discuss how to return an array in java.

In order to return an array in java we need to take care of the following points:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

Keypoint 1: Method returning the array must have the return type as an array of the same data type as that of the array being returned. The return type may be the usual Integer, Double, Character, String, or user-defined class objects as well.

// Method returning an String array.
int[] methodName() {...}
// Method returning a String array.
String[] methodName() {...}
// Method returning an array of objects of class named Students.
Students[] methodName() {...} 

Keypoint 2: Access modifiers must be used accurately considering the usage of the method and the returning array. Static and non-static declarations must also be taken into consideration.



// Using public access modifier and static to call the method from a static class, method or block.
public static char[] methodName() {...} 

Keypoint 3: There must be any variable array of the same data type or something similar at the method call to handle the array being returned. For example, an integer array returned from any method can be stored as follows.

int[] storage = methodReturningArray();

Implementation:

To better understand this we can look into few different kinds of scenarios where we may be returning arrays. Here we will be considering three examples for scenarios.

  • Case 1: Simple Built-in arrays
  • Case 2: Array of objects
  • Case 3:

Case 1: Returning an integer (built-in data type) array in java

Any built-in data type’s array be integer, character, float, double all can be returned simply uses return statements keeping in mind the points listed above. 

Example

Java




// Java Program to Illustrate Returning
// simple built-in arrays
 
// Importing input output classes
import java.io.*;
 
// Main class
class GFG {
 
    // Method 1
    // Main driver method
    public static void main(String[] args)
    {
        // An integer array storing the returned array
        // from the method
        int[] storage = methodReturningArray();
 
        // Printing the elements of the array
        for (int i = 0; i < storage.length; i++)
            System.out.print(storage[i] + " ");
    }
 
    // Method 2
    // Returning an integer array
    public static int[] methodReturningArray()
    {
        int[] sample = { 1, 2, 3, 4 };
 
        // Return statement of the method.
        return sample;
    }
}
Output
1 2 3 4 

Case 2: Returning an array of objects in java



This is done exactly in a similar manner in the case of returning arrays of built-in data types.

Example 

Java




// Java Program to Illustrate Returning
// an array of objects in java
 
// Importing all input output classes
import java.io.*;
 
// Class 1
// Helper class
// Courses whose objects are returned as an array
class Courses {
 
    String name;
    int modules;
 
    // Constructor to instantiate class objects.
    public Courses(String n, int m)
    {
        // This keyword refers to current instance  itself
        this.name = n;
        this.modules = m;
    }
}
 
// Class 2
// Main class
class GFG {
 
    // Method 1
    // Main driver method
    public static void main(String[] args)
    {
        // Calling the method for returning an array of
        // objects of the Courses class.
        Courses[] sample = methodReturningArray();
 
        // Printing the returned array elements.
        for (int i = 0; i < sample.length; i++)
            System.out.print(sample[i].name + " - "
                             + sample[i].modules
                             + " modules\n");
    }
 
    // Method 2
    // Note that return type is an array
    public static Courses[] methodReturningArray()
    {
        // Declaring Array of objects of the Courses class
        Courses[] arr = new Courses[4];
 
        // Custom array of objects
        arr[0] = new Courses("Java", 31);
        arr[1] = new Courses("C++", 26);
        arr[2] = new Courses("DSA", 24);
        arr[3] = new Courses("DBMS", 12);
 
        // Statement to return an array of objects
        return arr;
    }
}
Output
Java - 31 modules
C++ - 26 modules
DSA - 24 modules
DBMS - 12 modules

Case 3: Returning multidimensional arrays 

Multidimensional arrays in java can be said to be an array of arrays inside arrays. The simplest form can be a two-dimensional array. They have their sizes and declaration according to their sizes. Here returning of a two-dimensional array is demonstrated below that has a very similar approach to the one-dimensional arrays.

Example 

Java




// Java Program to Illustrate Returning
// Multi-dimensional Arrays
 
// Importing input output classes
import java.io.*;
 
// Main class
class GFG {
 
    // Method 1
    // Main driver method
    public static void main(String[] args)
    {
        // An integer 2D array storing the
        // returned array from the method
        int[][] storage = methodReturningArray();
 
        // Printing the elements of the array
        // using nested for loops
        for (int i = 0; i < storage.length; i++) {
            for (int j = 0; j < storage[0].length; j++)
 
                System.out.print(storage[i][j] + " ");
 
            System.out.println();
        }
    }
 
    // Method 2
    // Returning an integer array
    public static int[][] methodReturningArray()
    {
        // Custom 2D integer array
        int[][] sample
            = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
 
        // Return statement of the method
        return sample;
    }
}
Output
1 2 3 
4 5 6 
7 8 9 

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :