How to return an array in Java?23 Oct 2024 | 10 min read In Java, there are several ways to return an array from a method, each offering its own advantages and use cases. These methods can be broadly categorized into static arrays, dynamically created arrays, subarrays, and arrays generated using Java Streams. Firstly, one common approach is to return a static array that involves directly defining the array elements within the method and returning the array. This method is straightforward and useful when the array elements are known in advance and remain constant. For example, a method can return a static array containing predefined values such as {1, 2, 3, 4, 5}. In this section, we are going to learn how to return an array in Java. Remember:
Let us understand about arrays in detail with the help of a Java example program. Example 1:Filename: ArrayDemo.java Output: ![]() Example 2In the following example, the method returns an array of double type. Example 1Filename: ReturnArrayExample1.java Output: ![]() Example 2Filename: ReturnArrayExample2.java In the following example, the method returns an array of double type. Output: ![]() Example 3Filename: ReturnArrayExample3.java In the following example, method returns an array of object type. Output: ![]() Returning an Array in JavaBefore returning an array in Java, there are few important points that need to be taken care of and let us discuss them in detail in the following paragraphs.
ImplementationIn Java, returning arrays involves creating an array within a method and then returning it to the caller. For simple built-in arrays, which are arrays of primitive data types like int, double, char, etc., a method could generate and return an array of random integers. This process entails creating an array of integers of the specified size, populating it with random values, and then returning it to the caller. For example, a method `generateRandomIntArray(int size)` could be implemented to achieve this. When dealing with arrays of objects, where each element of the array is an object of a certain class, a method would create an array of objects, initialize the objects, and then return the array. For instance, a method `getPeople()` could be used to return an array of `Person` objects, with each `Person` object initialized with a name and age. This demonstrates the process of creating and returning arrays of objects. In scenarios involving multidimensional arrays, which are arrays of arrays, the method would create a multidimensional array, populate it with values, and then return it. For example, a method `getMultiplicationTable(int size)` could be implemented to return a 2D array representing a multiplication table of the specified size. This involves populating the array with the results of multiplying each pair of numbers from 1 to the specified size. Let's look at the implementation of the above-mentioned important points. For better understanding of this topic, let us look at the implementation of this topic in three different situations. 1. Returning a Built-in Array In this scenario or situation, we will be returning an array which will be of the basic data type available in the Java such as int, float, char, Boolean ,double, long, short , etc. Filename: ArrayReturn.java Output: 1 2 3 4 2. An Array of Objects Being Returned We can return an array of objects in the same way an array of default data types gets returned. Let us look at the implementation of the above-mentioned point. Filename: ArrayReturn1.java Output: Java - 31 modules C++ - 26 modules DSA - 24 modules DBMS - 12 modules 3. Return a Multi-Dimensional Array Multidimensional array can be described as arrays which are store inside arrays. The best example of a multidimensional array can be a 2-D array. The declaration and sizes of multidimensional arrays are based on their sizes. Let us understand the implementation of how a multidimensional array (2D array) is returned using a method in Java. Filename: ArrayReturn3.java Output: Printing the returned array: 1 2 3 4 5 6 7 8 9 10 11 12 Accessing specific elements: Element at [0][0]: 1 Element at [1][2]: 7 Element at [2][1]: 10 Sum of all elements: 78 Let's understand about how to return an array in Java in detail with the help of a Java example program. Filename: ReturnArrayExamples.java Output: Static Array: [1, 2, 3, 4, 5] Dynamic Array: [1, 2, 3, 4, 5] Subarray using Arrays.copyOfRange: [2, 3] Subarray using System.arraycopy: [2, 3] Array using Java Streams: [1, 2, 3, 4, 5] Next TopicJava Tutorial |
In this section, we will create Java programs that add digits of a number until the number becomes a single-digit number. The problem is also known as the digit root problem. Example Suppose, 76345 is a number for which we have to find the sum until it becomes...
3 min read
In this section, we will learn about finding the cake number in Java. The cake number CKn represents the maximum number of pieces a cake can be divided with the help of n planar cuts. The tridimensional version of the pancake numbers is the cake numbers. In...
6 min read
Given two integers, n and k. We begin with an array an of n integers at first, such that for every 0 <= i <= n - 1, such that a[i] = 1. We simultaneously update each element after every second so that it is...
3 min read
Cyclic permutation of array elements is a fundamental technique in computer science, used to rotate elements within a fixed-size array such that each element shifts one position to the right, with the last element wrapping around to the first position. This operation is essential in various...
4 min read
Just like the Red-Black Tree, the AVL tree is another self-balancing BST(Binary Search Tree) in Java. In the AVL tree, the difference between heights of the right and left subtree doesn't exceed one for all nodes. It takes O(h) time to perform the search, max, min,...
6 min read
For processing the objects collections, Java 8 is introduced. A stream is nothing but the objects sequence that give support to the different methods that can be pipelined for producing the result that is required. Before proceeding with this topic further, it is advised to...
8 min read
In Java, converting a Set to a List can be achieved using several methods, each with its own advantages: Using the ArrayList Constructor is often the most concise and common way. We can directly pass the Set instance to the constructor of an ArrayList. There are...
5 min read
A Giuga Number is a composite number N that has a unique property. The property states that for every prime factor, p of N, N divided by p minus 1 ((N/p) - 1) should also be divisible by p. If a number N satisfies this condition...
5 min read
Juggler Sequence In number theory, Juggler Sequence consists of numbers beginning with a positive integer n, where each subsequent term is determined by whether the ious term is even or odd. The sequence continues until it reaches 1. How to find Juggler Sequence? Juggler sequence is defined recursively as...
7 min read
The Power Set of a set denotes the ensemble of all possible subsets, which includes both the empty subset and the original set. If a collection contains n elements, the power set will consist of 2^n subsets. This happens because each element in the set can...
8 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India