How to Return an Array in Java

How to Return an Array in Java

6 mins read187 Views Comment
Esha
Esha Gupta
Associate Senior Executive
Updated on Mar 22, 2024 16:21 IST

In Java, methods can return arrays to provide multiple data elements of a consistent type in a single response. There are various ways on how to return an array. Let’s understand more about it!

2023_09_What-is-18 p1.jpg

Arrays in Java play a fundamental role in storing and managing collections of similar data types. A common practice when working with methods is to return an array, allowing dynamic data to be organized and easily transferred between parts of a program. This blog will help you learn “How to return an array in Java”!

Table of Content

Recommended online courses

Best-suited Java courses for you

Learn Java with these high-rated online courses

– / –
350 hours
Free
6 months
– / –
4 months
– / –
– / –
– / –
1 month
50 K
7 weeks
7.8 K
3 months
8.47 K
2 months
7 K
6 months
4 K
2 months

What is an Array in Java?

An array is a fixed-size, ordered collection of elements of the same data type. Elements can be accessed by their index, starting from 0.

Must Read Array Programs in Java | Beginner to Expert Level

Why Return an Array?

Returning an array from a method allows you to:

  • Organize data effectively.
  • Enhance code reusability.
  • Simplify code by grouping related values.
  • Pass dynamic-sized data between methods.

How to Return an Array from a Method?

Syntax

public static dataType[] methodName() {
    // ... method body
    return arrayName;
}

Where dataType can be any valid data type in Java, like int, double, String, etc.

Returning a One-dimensional Array

To return an array, you declare the method’s return type as the array type and then use the return statement to return the array.

Example


 
public class Main {
public static void main(String[] args) {
int[] returnedArray = generateNumbers();
for (int i : returnedArray) {
System.out.print(i + " ");
}
}
public static int[] generateNumbers() {
int[] numbers = {1, 2, 3, 4, 5};
return numbers;
}
}
Copy code

Output

1 2 3 4 5 

The code prints 1 2 3 4 5 which confirms that it is returning and processing a one-dimensional array.

Returning a Multi-dimensional Array

Similar to one-dimensional arrays, but with added dimensions.

Example


 
public class Main {
public static void main(String[] args) {
int[][] returnedMatrix = generateMatrix();
for (int i = 0; i < returnedMatrix.length; i++) {
for (int j = 0; j < returnedMatrix[i].length; j++) {
System.out.print(returnedMatrix[i][j] + " ");
}
System.out.println(); // Move to the next line after printing each row
}
}
public static int[][] generateMatrix() {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
return matrix;
}
}
Copy code

Output

1 2 3 
4 5 6 
7 8 9 

This confirms the code returns and processes a two-dimensional array (matrix).

Best Practices When Returning Arrays

  • Ensure the array’s size and content match the method’s intended purpose.
  • Avoid returning large arrays to save memory.
  • If the array data shouldn’t be modified, consider returning a cloned version or using collections that offer immutability.
 

Common Mistakes and How to Avoid Them

  • Returning null: This can lead to NullPointerException. Ensure you always return a valid array or handle null scenarios.
  • Modifying Returned Arrays: Since arrays are objects, changes in returned arrays can affect the original. Always be cautious when modifying arrays returned by methods.

Real-Life Example

Problem Statement:

Imagine you are building a system for a bookstore. This system needs a feature that, given a list of books and authors, can return an array of book titles by a specific author.

The user will be able to:

  1. Add books to the bookstore inventory.
  2. Query the inventory to find all books by a specific author, which will be returned as an array of titles.

Requirements:

  1. Create a Book class that represents a book, with attributes for the title and author.
  2. Create a BookStore class that represents the bookstore, with methods to add a book and to get books by author.
  3. Demonstrate adding books to the bookstore and querying for books by a specific author.

Code


 
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
BookStore store = new BookStore();
store.addBook(new Book("1984", "George Orwell"));
store.addBook(new Book("To Kill a Mockingbird", "Harper Lee"));
store.addBook(new Book("Animal Farm", "George Orwell"));
String[] booksByOrwell = store.getBooksByAuthor("George Orwell");
System.out.println("Books by George Orwell:");
for (String title : booksByOrwell) {
System.out.println(title);
}
}
}
class Book {
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
}
class BookStore {
private ArrayList<Book> books;
public BookStore() {
books = new ArrayList<>();
}
public void addBook(Book book) {
books.add(book);
}
public String[] getBooksByAuthor(String author) {
ArrayList<String> result = new ArrayList<>();
for (Book book : books) {
if (book.getAuthor().equalsIgnoreCase(author)) {
result.add(book.getTitle());
}
}
return result.toArray(new String[0]);
}
}
Copy code

Output

Books by George Orwell:
1984
Animal Farm

How It Works:

  • The Book class is used to represent a book, with title and author as attributes.
  • The BookStore class represents the bookstore and contains an ArrayList of Book objects. It has a addBook method to add a book to the store and a getBooksByAuthor method to retrieve book titles by a specific author.
  • In the Main class, we add books to the BookStore and then query the store for books by George Orwell, which will return an array of book titles.

This example effectively shows how to return an array in Java, aligning with a realistic software product requirement of handling a bookstore inventory and providing book search functionality based on the author’s name.

Array Programs in Java | Beginner to Expert Level
Array Programs in Java | Beginner to Expert Level
Array programs in Java traverse from basic single-dimensional arrays to complex multi-dimensional arrays and dynamic arrays using ArrayList. From initializing and accessing array elements, to advanced operations like sorting and...read more
Understanding ArrayList in Java
Understanding ArrayList in Java
An ArrayList in Java is an array that resizes itself as needed. It is also popularly known as a resizable array. The article below explains ArrayList in Java with suitable...read more
Understanding Data Structures and Algorithms in Java
Understanding Data Structures and Algorithms in Java
Data Structure in Java is used to store and organize data efficiently while the algorithms are used to manipulate the data in that structure. In this article, we will briefly...read more

Some More Miscellaneous Examples

Example 1: Returning a Dynamic Array


 
public class Main {
public static void main(String[] args) {
// Example usage: Generate an array of size 5, starting with value 10
int[] generatedArray = generateDynamicArray(5, 10);
// Printing the generated array
for (int value : generatedArray) {
System.out.print(value + " ");
}
}
/**
* Generates an array of a given size, starting with a specified start value.
*
* @param size the size of the array to be generated
* @param startValue the starting value of the array
* @return an array of integers
*/
public static int[] generateDynamicArray(int size, int startValue) {
int[] result = new int[size];
for (int i = 0; i < size; i++) {
result[i] = startValue + i;
}
return result;
}
}
Copy code

Output

10 11 12 13 14 

Example 2: Returning an Array of Strings


 
public class Main {
public static void main(String[] args) {
String[] days = getDaysOfWeek();
for (String day : days) {
System.out.println(day);
}
}
public static String[] getDaysOfWeek() {
return new String[]{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
}
}
Copy code

Output

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Example 3: Returning an Array of Objects


 
public class Main {
public static void main(String[] args) {
Person[] familyMembers = getFamilyMembers();
for (Person member : familyMembers) {
System.out.println(member.getName());
}
}
public static Person[] getFamilyMembers() {
return new Person[]{new Person("Rekha"), new Person("Granth"), new Person("Neeraj")};
}
}
class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
// ... (other methods and attributes)
}
Copy code

Output

Rekha
Granth
Neeraj

Example 4: Returning a Jagged Array


 
public class Main {
public static void main(String[] args) {
int[][] jaggedArray = getJaggedArray();
for (int[] innerArray : jaggedArray) {
for (int num : innerArray) {
System.out.print(num + " ");
}
System.out.println();
}
}
public static int[][] getJaggedArray() {
return new int[][]{
{1},
{2, 3},
{4, 5, 6}
};
}
}
Copy code

Output

1 
2 3 
4 5 6 

Arrays in Java can be “jagged”, meaning they can have rows of different lengths.

Example 5: Returning an Array with Values from a Collection


 
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
// Creating a sample set of integers
Set<Integer> sampleSet = new HashSet<>();
sampleSet.add(10);
sampleSet.add(40);
sampleSet.add(60);
// Converting the set to an array using the provided method
Integer[] resultArray = returnArrayFromSet(sampleSet);
// Printing the elements of the resulting array
for (Integer num : resultArray) {
System.out.println(num);
}
}
public static Integer[] returnArrayFromSet(Set<Integer> set) {
return set.toArray(new Integer[0]);
}
}
Copy code

Output

40
10
60

Example 6: Returning an Empty Array


 
public class Main {
public static void main(String[] args) {
// Getting an empty array of strings
String[] resultArray = getNoData();
// Printing the size of the resulting array
System.out.println("Size of the array: " + resultArray.length);
// Trying to print elements (This loop won't run since the array is empty)
for (String str : resultArray) {
System.out.println(str);
}
}
public static String[] getNoData() {
return new String[0];
}
}
Copy code

Output

Size of the array: 0

Example 7: Returning Arrays of Primitive Data Types Other than int


 
public class Main {
public static void main(String[] args) {
// Getting the char array from the method
char[] resultArray = returnCharArray();
// Printing the characters of the resulting array
for (char ch : resultArray) {
System.out.println(ch);
}
}
// Method to return a char array
public static char[] returnCharArray() {
return new char[]{'a', 'b', 'c'};
}
}
Copy code

Output

a
b
c

Example 8: Returning Arrays with Variable Sizes


 
public class Main {
public static void main(String[] args) {
// Example usage: Generate an array of size 7
int[] resultArray = returnArrayWithVariableSize(7);
// Initialize and print the array
for (int i = 0; i < resultArray.length; i++) {
resultArray[i] = i * 10; // Sample initialization
System.out.println(resultArray[i]);
}
}
// Method to return an int array of a given size
public static int[] returnArrayWithVariableSize(int size) {
return new int[size];
}
}
Copy code

Output

0
10
20
30
40
50
60

Thus, the ability to return arrays in Java enhances modularization, code reusability, and data encapsulation. Whether you’re a beginner or an expert, this article will definitely help you to clear the concept of returning arrays in Java. Keep learning, Keep exploring!

FAQs

How do you indicate that a Java method returns an array?

In Java, you indicate that a method returns an array by specifying the array type in the method signature followed by square brackets ([]). For example, public int[] myMethod() indicates that myMethod returns an array of integers.

Can a Java method return arrays of different types?

Yes, a Java method can return arrays of different types, including arrays of primitive types (like int[], double[], etc.) or arrays of objects (like String[], Object[], etc.).

Is it possible to pass an array as a parameter to a method in Java?

Yes, in Java, you can pass an array as a parameter to a method by specifying the array type followed by square brackets ([]) in the method signature. For example, public void myMethod(int[] arr) indicates that myMethod takes an integer array as a parameter.

What happens if a Java method returns a null array?

If a Java method returns a null array, it means that the method is not returning any valid array object. Any attempt to access or manipulate elements of the returned array may result in a NullPointerException because null arrays do not have any elements and cannot be dereferenced.

How can you modify an array returned by a method in Java?

In Java, you can modify an array returned by a method by first receiving the returned array in a variable and then directly manipulating its elements. Since arrays are objects in Java, changes made to the array's elements within the calling code will reflect in the original array.

About the Author
author-image
Esha Gupta
Associate Senior Executive

Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio