Different methods to return an array in Java
In Java, an array is a container object that can hold a fixed number of values of same type. The length of array is declared at time of creation of an array. Java allows arrays to be passed as a parameter to the other functions and return data from that function. In fact, if we need to return multiple value of same type then returning through an array is the best alternative. Moreover, java always passes an array by reference, so any modification done by the other function would always modify the original array.
There are three different ways to return an array from a function in Java as listed below.
- Return an array of primitive type
- Return an array of objects
- Return a multidimensional array
Method-1: Return an array of primitive type
We can use this approach, if we want to return multiple values of same type from a function. As we know that java does not support return statement with multiple values. So, we can use this concept to return multiple value of any primitive type like int, char, float, double, long etc. from a function.
Example : In this example, we are having a readIntArray()
function that returns an integer array. Moreover, we have also used add100()
function that adds 100 to each element of an array. As, Java passes array by reference all the modifications done are visible even without returning an array from add100 function.
// Program to demonstrate return an array of primitive type
public class ArrayDemo {
public static void main(String[] args) {
// Creating object of class
ArrayDemo m = new ArrayDemo();
// Declaring array and calling function to read array
int a[] = m.readIntArray();
// Printing the content of an array
System.out.println("Array returned by readIntArray function");
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
// Calling a function to add 100 to each element in an array
m.add100(a);
// Printing the content of an array
System.out.println("Array after add100 function");
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
// function that adds 100 to each element - array passed by reference
void add100(int x[]) {
for (int i = 0; i < x.length; i++) {
x[i] = x[i] + 100;
}
}
// Function that returns an array
int[] readIntArray() {
int a[] = {
1,
2,
3,
4
};
return a;
}
}
Output
Array returned by readIntArray function
1
2
3
4
Array after add100 function
101
102
103
104
Method-2: Return an array of objects
We can use this approach when we need to return multiple objects from the class. It works in the same way as a primitive type array. In other words, we can wrap a multiple type of value inside a class object and return multiple objects from the class.
Example : In this example, we are returning an array of student objects using getStudents()
method. Thereafter, it calls the constructor to initialize the name and marks. We are then printing the student marks in a main class.
// Program to return an array of objects
import java.io.*;
class Student {
// Declaring class variables
String name;
int marks;
// Constructor to instantiate class objects.
public Student(String n, int m) {
// this keyword refers to current instance itself
this.name = n;
this.marks = m;
}
}
class Main {
public static void main(String[] args) {
// Calling the method for returning an array of objects of the Student class.
Student[] s = getStudents();
// Printing
for (int i = 0; i < s.length; i++)
System.out.print(s[i].name + " - " + s[i].marks + " marks\n");
}
// Function returning an array of objects
public static Student[] getStudents() {
// Declaring Array of objects of the Student class
Student[] a = new Student[4];
// Custom array of objects
a[0] = new Student("Ram", 91);
a[1] = new Student("John", 66);
a[2] = new Student("Dora", 29);
a[3] = new Student("Sim", 58);
// Returning an array of objects
return a;
}
}
Output
Ram - 91 marks
John - 66 marks
Dora - 29 marks
Sim - 58 marks
Method-3: Return a Multidimensional array
In this approach, we return a multidimensional array from a function. However, it works on the same way as a single dimensional array. The only difference is we have to give multiple [] brackets to indicate the return type.
Example : In this example, we are adding two dimensional arrays and returning from a function.
// Program to return a multidimensional array
import java.io.*;
class Main {
public static void main(String[] args) {
// Creating object of a class.
Main m = new Main();
// Initializing an array
int a[][] = {
{
1,
1,
1
},
{
1,
1,
1
},
{
1,
1,
1
}
};
// Calling a method to add two arrays
int c[][] = m.add(a);
// Computing no. of rows and columns in array returned from the function
int r = c.length, col = c[0].length;
// Printing the result
System.out.println("Addition of two array is ");
for (int i = 0; i < r; i++) {
for (int j = 0; j < col; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
// Function that adds two array and return a result as an array
int[][] add(int x[][]) {
int y[][] = {
{
1,
1,
1
},
{
1,
1,
1
},
{
1,
1,
1
}
};
int r = x.length;
int c = x[0].length;
int z[][] = new int[r][c];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
z[i][j] = x[i][j] + y[i][j];
}
}
return z;
}
}
Output
Addition of two array is
2 2 2
2 2 2
2 2 2
Examples to Return an array from a function
Example 1 : Find repeated words in a string using for loop and while loop
In this example, we have a string containing some repeated words. Here, we are finding the list of words repeated in the given String. For this task, we have to convert String into an array of words which is done using user defined function intowords()
that returns an array.
public class Main {
public static void main(String[] args) {
// Declaring and initializing the variables
String s = "Life is like a book. Life is like a cup of tea. Life is like a rose garden. Life is like a dream";
int count;
// Object creation
Main m = new Main();
//Converts the string into lowercase
s = s.toLowerCase();
// Calling a function to convert string to words array
String w[] = m.intowords(s);
// Finding repeated words in the string
System.out.println("Finding repeated words in a string : ");
int i = 0;
while (i < w.length) {
count = 1;
for (int j = i + 1; j < w.length; j++) {
if (w[i].equals(w[j])) {
count++;
// Setting w[j] to 0 again to avoid printing visited word
w[j] = "0";
}
}
//Displays the repeated word if count is greater than 1
if (count > 1 && w[i] != "0")
System.out.println(w[i]);
i++;
}
}
// Splitting the string to words for comparision
String[] intowords(String x) {
String w[] = x.split(" ");
return w;
}
}
Output
Finding repeated words in a string :
life
is
like
a
Example 2 : Return a float array from a function
In this example, we are having a function getvalue() consisting of three float variables that is required to be returned to main. So, we create an float array to return the same.
// Program to return an array from a function
class Main {
public static float[] getvalue() {
float a1 = 10.5f;
float a2 = 20.5f;
float a3 = 30.5f;
return new float[] {
a1,
a2,
a3
}; //returns array
}
public static void main(String args[]) {
float[] a = getvalue();
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}
Output
10.5
20.5
30.5
Summary
The knowledge of Returning an array from a function in Java is very useful while working on a real time applications. It’s important to note that in java arrays are passed as a reference so any modifications done outside the function is visible to the original array. In this tutorial, we covered three different approaches to return an array in Java. As per the requirement of an application, we can choose an appropriate approach. We learned in detail about this approaches with an example. All in all, this tutorial, covers everything that you need to know in order to have a clear view on returning an array in Java.
References