0% found this document useful (0 votes)
27 views

How To Return An Array in Java

Uploaded by

crystaljhoyl
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

How To Return An Array in Java

Uploaded by

crystaljhoyl
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

How to Return an Array in Java

Esha Gupta
Asso ciate Senio r Executive

Updated on Oct 3, 2023 11:32 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!

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

What is an Array in Java?

Why Return an Array?

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
How to Return an Array from a Method?
Syntax

Returning a One-dimensional Array

Returning a Multi-dimensional Array

Best Practices When Returning Arrays

Common Mistakes and How to Avoid T hem

Real-Life Example

Some More Miscellaneous Examples

Conclusion

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 ef f ectively.

Enhance code reusability.

Simplif y code by grouping related values.

Pass dynamic-sized data between methods.

How to Return an Array f rom a Method?

Synt ax

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
public static dataT ype[] methodName() {
// ... method body
return arrayName;
}

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

Ret urning 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

Copy code

public class Main {

public st at ic void main(St ring[] args) {


int [] ret urnedArray = generat eNumbers();
f or (int i : ret urnedArray) {
Syst em.out .print (i + " ");
}
}

public st at ic int [] generat eNumbers() {


int [] numbers = {1, 2, 3, 4, 5};
ret urn numbers;
}
}

Output

12345

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
The code prints 1 2 3 4 5 which confirms that it is returning and processing a one-
dimensional array.

Ret urning a Mult i-dimensional Array

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

Example

Copy code

public class Main {

public st at ic void main(St ring[] args) {


int [][] ret urnedMat rix = generat eMat rix();
f or (int i = 0; i < ret urnedMat rix.lengt h; i++) {
f or (int j = 0; j < ret urnedMat rix[i].lengt h; j++) {
Syst em.out .print (ret urnedMat rix[i][j] + " ");
}
Syst em.out .print ln(); // Move to the next line after printing each row
}
}

public st at ic int [][] generat eMat rix() {


int [][] mat rix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
ret urn mat rix;
}
}

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Output

123
456
789

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 modif ied, consider returning a cloned version or using
collections that of f er immutability.

Common Mistakes and How to Avoid Them

Returning null: T his 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
af f ect the original. Always be cautious when modif ying arrays returned by methods.

Real-Lif e 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 f ind all books by a specif ic author, which will be returned as an
array of titles.

Requirements:

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Create a Book class that represents a book, with attributes f or 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 f or books by a specif ic


author.

Code

Copy code

import java.ut il.ArrayList ;

public class Main {

public st at ic void main(St ring[] args) {


BookSt ore st ore = new BookSt ore();
st ore.addBook(new Book("1984", "George Orwell"));
st ore.addBook(new Book("T o Kill a Mockingbird", "Harper Lee"));
st ore.addBook(new Book("Animal Farm", "George Orwell"));

St ring[] booksByOrwell = st ore.get BooksByAut hor("George Orwell");


Syst em.out .print ln("Books by George Orwell:");
f or (St ring t it le : booksByOrwell) {
Syst em.out .print ln(t it le);
}
}
}

class Book {
privat e St ring t it le;
privat e St ring aut hor;

public Book(St ring t it le, St ring aut hor) {

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
public Book(St ring t it le, St ring aut hor) {
t his.t it le = t it le;
t his.aut hor = aut hor;
}

public St ring get T it le() {


ret urn t it le;
}

public St ring get Aut hor() {


ret urn aut hor;
}
}

class BookSt ore {


privat e ArrayList <Book> books;

public BookSt ore() {


books = new ArrayList <>();
}

public void addBook(Book book) {


books.add(book);
}

public St ring[] get BooksByAut hor(St ring aut hor) {


ArrayList <St ring> result = new ArrayList <>();
f or (Book book : books) {
if (book.get Aut hor().equalsIgnoreCase(aut hor)) {
result .add(book.get T it le());
}
}
ret urn result .t oArray(new St ring[0]);
}

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
}

Output

Books by George Orwell:


1984
Animal Farm

How It Works:

T he Book class is used to represent a book, with title and author as attributes.

T he 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 specif ic author.

In the Main class, we add books to the BookStore and then query the store f or 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 t o Expert Level


Array pro grams in Java traverse fro m basic single-dimensio nal arrays to
co mplex multi-dimensio nal arrays and dynamic arrays using ArrayList. Fro m
initializing and accessing array elements, to advanced o peratio ns like so rting
and...re ad m o re

Underst anding ArrayList in Java


The belo w article go es thro ugh explaining ArrayList in Java with suitable
examples. It co vers the creatio n and o peratio ns o n ArrayList alo ng with a few
metho ds in it. Let’s begin!

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Underst anding Dat a St ruct ures and Algorit hms in Java
Data Structure in Java is used to sto re and o rganize data efficiently while the
algo rithms are used to manipulate the data in that structure. In this article, we will
briefly...re ad m o re

Some More Miscellaneous Examples

Example 1: Retu rning a Dynamic Array

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code

public class Main {

public st at ic void main(St ring[] args) {


// Example usage: Generate an array of size 5, starting with value 10
int [] generat edArray = generat eDynamicArray(5, 10);

// Printing the generated array


f or (int value : generat edArray) {
Syst em.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 st at ic int [] generat eDynamicArray(int size, int st art Value) {
int [] result = new int [size];
f or (int i = 0; i < size; i++) {
result [i] = st art Value + i;
}
ret urn result ;
}
}

Output

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
10 11 12 13 14

Example 2: Returning an Array of Strings

Copy code

public class Main {

public st at ic void main(St ring[] args) {


St ring[] days = get DaysOf Week();

f or (St ring day : days) {


Syst em.out .print ln(day);
}
}

public st at ic St ring[] get DaysOf Week() {


ret urn new St ring[]{"Sunday", "Monday", "T uesday", "Wednesday", "T hursday",
}
}

Output

Sunday
Monday
T uesday
Wednesday
T hursday
Friday
Saturday

Example 3: Returning an Array of Objects

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code

public class Main {

public st at ic void main(St ring[] args) {


Person[] f amilyMembers = get FamilyMembers();

f or (Person member : f amilyMembers) {


Syst em.out .print ln(member.get Name());
}
}

public st at ic Person[] get FamilyMembers() {


ret urn new Person[]{new Person("Rekha"), new Person("Grant h"), new Person("Neeraj"
}
}

class Person {
privat e St ring name;

public Person(St ring name) {


t his.name = name;
}

public St ring get Name() {


ret urn name;
}

// ... (other methods and attributes)


}

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Output

Rekha
Granth
Neeraj

Example 4: Returning a Jagged Array

Copy code

public class Main {

public st at ic void main(St ring[] args) {


int [][] jaggedArray = get JaggedArray();

f or (int [] innerArray : jaggedArray) {


f or (int num : innerArray) {
Syst em.out .print (num + " ");
}
Syst em.out .print ln();
}
}

public st at ic int [][] get JaggedArray() {


ret urn new int [][]{
{1},
{2, 3},
{4, 5, 6}
};
}
}

Output

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
1
23
456

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

Example 5: Returning an Array with Values from a Collection

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code

import java.ut il.HashSet ;


import java.ut il.Set ;

public class Main {

public st at ic void main(St ring[] args) {


// Creating a sample set of integers
Set <Int eger> sampleSet = new HashSet <>();
sampleSet .add(10);
sampleSet .add(40);
sampleSet .add(60);

// Converting the set to an array using the provided method


Int eger[] result Array = ret urnArrayFromSet (sampleSet );

// Printing the elements of the resulting array


f or (Int eger num : result Array) {
Syst em.out .print ln(num);
}
}

public st at ic Int eger[] ret urnArrayFromSet (Set <Int eger> set ) {


ret urn set .t oArray(new Int eger[0]);
}
}

Output

40
10

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
60

Example 6: Returning an Empty Array

Copy code

public class Main {

public st at ic void main(St ring[] args) {


// Getting an empty array of strings
St ring[] result Array = get NoDat a();

// Printing the size of the resulting array


Syst em.out .print ln("Size of t he array: " + result Array.lengt h);

// Trying to print elements (This loop won't run since the array is empty)
f or (St ring st r : result Array) {
Syst em.out .print ln(st r);
}
}

public st at ic St ring[] get NoDat a() {


ret urn new St ring[0];
}
}

Output

Size of the array: 0

Example 7: Returning Arrays of Primitive Data T ypes Other than int

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code

public class Main {

public st at ic void main(St ring[] args) {


// Getting the char array from the method
char[] result Array = ret urnCharArray();

// Printing the characters of the resulting array


f or (char ch : result Array) {
Syst em.out .print ln(ch);
}
}

// Method to return a char array


public st at ic char[] ret urnCharArray() {
ret urn new char[]{'a', 'b', 'c'};
}
}

Output

a
b
c

Example 8: Returning Arrays with Variable Sizes

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
Copy code

public class Main {

public st at ic void main(St ring[] args) {


// Example usage: Generate an array of size 7
int [] result Array = ret urnArrayWit hVariableSize(7);

// Initialize and print the array


f or (int i = 0; i < result Array.lengt h; i++) {
result Array[i] = i * 10; // Sample initialization
Syst em.out .print ln(result Array[i]);
}
}

// Method to return an int array of a given size


public st at ic int [] ret urnArrayWit hVariableSize(int size) {
ret urn new int [size];
}
}

Output

0
10
20
30
40
50
60

Conclusion

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.
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!

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 1-No v-20 23.

You might also like