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
import java.io.*;
class GFG {
public static void main(String[] args)
{
int [] storage = methodReturningArray();
for ( int i = 0 ; i < storage.length; i++)
System.out.print(storage[i] + " " );
}
public static int [] methodReturningArray()
{
int [] sample = { 1 , 2 , 3 , 4 };
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
import java.io.*;
class Courses {
String name;
int modules;
public Courses(String n, int m)
{
this .name = n;
this .modules = m;
}
}
class GFG {
public static void main(String[] args)
{
Courses[] sample = methodReturningArray();
for ( int i = 0 ; i < sample.length; i++)
System.out.print(sample[i].name + " - "
+ sample[i].modules
+ " modules\n" );
}
public static Courses[] methodReturningArray()
{
Courses[] arr = new Courses[ 4 ];
arr[ 0 ] = new Courses( "Java" , 31 );
arr[ 1 ] = new Courses( "C++" , 26 );
arr[ 2 ] = new Courses( "DSA" , 24 );
arr[ 3 ] = new Courses( "DBMS" , 12 );
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
import java.io.*;
class GFG {
public static void main(String[] args)
{
int [][] storage = methodReturningArray();
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();
}
}
public static int [][] methodReturningArray()
{
int [][] sample
= { { 1 , 2 , 3 }, { 4 , 5 , 6 }, { 7 , 8 , 9 } };
return sample;
}
}
|
Similar Reads
Set to Array in Java
Given a set (HashSet or TreeSet) of strings in Java, convert it into an array of strings. Input : Set hash_Set = new HashSet(); hash_Set.add("Geeks"); hash_Set.add("For"); Output : String arr[] = {"Geeks", "for"} Method 1 (Simple) We simply create an empty array. We traverse the given set and one by
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 commo
4 min read
How to Initialize an Array in Java?
An array in Java is a linear data structure, which is used to store multiple values of the same data type. In 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.
6 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 code for converting string array // to str
3 min read
How to Find Length or Size of an Array in Java?
Finding the length of an array is a very common and basic task in Java programming. Knowing the size of an array is essential so that we can perform certain operations. In this article, we will discuss multiple ways to find the length or size of an array in Java. In this article, we will learn: How
3 min read
How to Add an Element to an Array in Java?
In Java, arrays are of fixed size, and we can not change the size of an array dynamically. We have given an array of size n, and our task is to add an element x into the array. In this article, we will discuss the New Different Ways to Add an Element to an ArrayThere are two different approaches we
3 min read
How to Pass 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 ca
2 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
How to Create Array of Objects in Java?
In Java, an array of objects is used to store multiple instances of a class within a single array. This allows us to easily manage a collection of objects when working with large datasets or collections. Example: In the below example, we will demonstrate how to create an array of Student objects and
5 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