How to Return an Array in Java
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!
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
Best-suited Java courses for you
Learn Java with these high-rated online courses
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; }}
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; }}
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:
- Add books to the bookstore inventory.
- Query the inventory to find all books by a specific author, which will be returned as an array of titles.
Requirements:
- Create a Book class that represents a book, with attributes for the title and author.
- Create a BookStore class that represents the bookstore, with methods to add a book and to get books by author.
- 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]); }}
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.
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; }}
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"}; }}
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)}
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} }; }}
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]); }}
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]; }}
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'}; }}
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]; }}
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.
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