How to Return an Array in Java?
Last Updated :
29 Jun, 2022
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:
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 integer 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: Returning multidimensional arrays
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;
}
}
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;
}
}
OutputJava - 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;
}
}
Similar Reads
How to Declare an Array in Java? In Java programming, arrays are one of the most essential data structures used to store multiple values of the same type in a single variable. Understanding how to declare an array in Java is very important. In this article, we will cover everything about array declaration, including the syntax, dif
3 min read
Reverse an Array in Java Reversing an Array is a common task in every programming language. In Java, there are multiple ways to reverse an array. We can reverse it manually or by using built-in Java methods. In this article, we will discuss different methods to reverse an array with examples.Let us first see the most common
4 min read
Array to Stream in Java Prerequisite : Stream In Java Using Arrays.stream() : Syntax : public static <T> Stream<T> getStream(T[] arr) { return Arrays.stream(arr); } where, T represents generic type. Example 1 : Arrays.stream() to convert string array to stream. Java // Java code for converting string array // t
3 min read
How to Initialize an Array in Java? An array in Java is a linear data structure that is used to store multiple values of the same data type. In an array, each element has a unique index value, which makes it easy to access individual elements. We first need to declare the size of an array because the size of the array is fixed in Java
5 min read
Array getShort() method in Java The java.lang.reflect.Array.getShort() is an in-built method of Array class in Java and is used to return the element present at a given index from the specified Array as a short. Syntax: Array.getShort(Object []array,int index) Parameters: array: The object array whose index is to be returned. inde
3 min read
Convert List to Array in Java The List interface provides a way to store the ordered collection. It is a child interface of Collection. It is an ordered collection of objects where duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. Now here we are give
5 min read
Passing an Array to a Function in Java Passing an array to a function is an easy-to-understand task in Java. In this article, we will check how to pass an array as a method parameter.Caller Function Vs Called FunctionLet function GFG() be called from another function GFGNews(). Here, GFGNews is called the âCaller Functionâ and GFG is cal
2 min read
Array get() Method in Java The java.lang.reflect.Array.get() is an inbuilt method in Java and is used to return the element at a given index from the specified Array. Syntax Array.get(Object []array, int index) Parameters : This method accepts two mandatory parameters: array: The object array whose index is to be returned. in
3 min read
Array set() method in Java The java.lang.reflect.Array.set() is an inbuilt method in Java and is used to set a specified value to a specified index of a given object array. Syntax Array.set(Object []array, int index, Object value) Parameter : array : This is an array of type Object which is to be updated. index : This is the
3 min read
String Arrays in Java A String Array in Java is an array that stores string values. The string is nothing but an object representing a sequence of char values. Strings are immutable in Java, this means their values cannot be modified once created.When we create an array of type String in Java, it is called a String Array
5 min read