Как вернуть массив в java
Для возвращения массива в Java необходимо объявить возвращаемый тип метода как массив и вернуть этот массив из метода с помощью ключевого слова return . Например, чтобы вернуть массив целых чисел из метода, можно использовать следующий код:
public static int[] returnArray() int[] arr = 1, 2, 3, 4, 5>; return arr; >
В этом примере метод returnArray объявлен как public static int[] , что означает, что он возвращает массив целых чисел. Внутри метода создается массив arr и он возвращается с помощью ключевого слова return . После вызова метода можно сохранить возвращенный массив в переменной и использовать его дальше в коде.
How to Return Array in Java from Method
Return Array in Java | In the previous tutorial, we have learned how to pass an array as an argument to a method while calling a method.
Although we can pass an array when calling a method, we can also return an array from a method, just like other simple data types and objects.
When a method returns an array, actually, the reference of the array is returned. For example, we create a class called ReturnArray from a method named display().
When we will call display() method, it will return an array num of integers (i.e. integer array). Look at the following source code.
Program code:
package arraysProgram; public class ReturnArray < public int[ ] display() < int[] num = ; return num; // Returning the reference of array that refers to the array elements. > > public class Test < public static void main(String[] args) < ReturnArray obj = new ReturnArray(); int[ ] num = obj.display(); for(int i = 0; i < num.length; i++) < System.out.println("num[" +i+ "] https://www.scientecheasy.com/2021/08/one-dimensional-array-in-java.html/">one dimensional array as its argument and it is made to return one-dimensional array.The purpose of this method is to return a reference of array that refers to array elements, to a calling method.
In the main() method, we have called display() method using object reference variable obj and is to display them using for loop one by one on the console.
Now let’s understand the general syntax of how to return one dimensional and two-dimensional arrays from a method in java.Returning One dimensional Array from Method in Java
The general syntax of a method that can return a one dimensional array is as follows:
data-type[ ] method-name(argument) < // statements; // return arrayname; >Here, data-type represents the type of array being returned. The use of one pair of brackets ([ ]) indicates that the method is returning one-dimensional array of type data-type.
Arguments can be optional that can be a scalar type or array type. The return statement returns the array name without any brackets.
The syntax of calling a method is as follows:
data-type[ ] arrayname = obj-ref.method-name(arguments);Here, obj-ref is a reference to an object of the class of which the method is a member. The arguments (if any) are inputs to a method given from the calling method.
Let’s take a simple example program to compute the sum of elements in an array of integers.
Program code:
package arraysProgram; public class ArraySum < static int[ ] sum() < int[ ] data = ; return data; > public static void main(String[] args) < int sum = 0; int[ ] s = sum(); for(int i = 0; i < s.length; i++ ) < sum = sum + s[i]; >System.out.println("Sum of array elements: " +sum); > >Output: Sum of array elements: 150Returning Two dimensional Array from a Method in Java
We can also return two dimensional array from a method in java. The general syntax to declare a method that can return a two-dimensional array is as follows:
In the above syntax, the use of two pairs of square brackets indicates that the method returns two-dimensional array of type data-type.
The general syntax of calling a method is as follows:
data-type[ ][ ] arrayname = obj-ref.method-name(arguments);Let’s take an example program where we will return two-dimensional array from a method. In this program, we will take two-dimensional arrays of int type that will represent two matrices.
Then, we will add them and get them into another two-dimensional array of int type that represents sum matrix. This sum matrix will be displayed on the console.
Program code:
package arraysProgram; public class TDArray < void show(int x[ ][ ]) < for(int i = 0; i < x.length; i++) < for(int j = 0; j < x[i].length; j++) System.out.print(x[i][j]+ " "); System.out.println(); >> int[ ][ ] sum(int[ ][ ] x, int[ ][ ] y) < int[ ][ ] z = new int[x.length][x[0].length]; for(int i = 0; i < x.length; i++) for(int j = 0; j < x[i].length; j++) z[i][j] = x[i][j] + y[i][j]; return z; // Returning 2D array. >> public class TDArrayfromMethod < public static void main(String[ ] args) < int[ ][ ] x = , >; int[ ][ ] y = , >; int[ ][ ] z = new int[x.length][x[0].length]; // Create an object of class TDArray. TDArray obj = new TDArray(); System.out.println("Matrix x: "); obj.show(x); System.out.println("Matrix y: "); obj.show(y); z = obj.sum(x, y); System.out.println("Matrix z: "); obj.show(z); > >Output: Matrix x: 1 2 3 4 Matrix y: 5 6 7 8 Matrix z: 6 8 10 12In this program, we have created a class TDArray with two methods show() and sum(). The show() method is declared with a two dimensional array as its argument.
The purpose of this method is to print elements of array passed to it. The sum() method is declared with two 2D arrays as its arguments and made to return a two dimensional array.
The function of this method is to display the sum of two 2D arrays passed to it and return the sum array (two dimensional array) to calling method.
In the main() method of class TDArrayfromMethod, two-dimensional arrays x and y are created with their values initialized and they are printed on the console.
After that the sum of arrays is calculated and assigned to another two-dimensional array z with statement z = obj.sum(x, y);. The sum array is then displayed on the console.
In this way, we can also think of passing and returning arrays of even arrays of higher dimensional also from a method.
4. Let’s take an example program where we will find out the list of prime numbers between the given two numbers. In this example, we will use Scanner class to get input from the keyboard. Concentrate on the following source code to understand better.
Program code:
package arraysProgram; public class Primes < // Test and return true if a number n is prime. static boolean prime(int n) < // Initially, isPrime is set to true. It become false if n is not prime. boolean isPrime = true; for(int i = 2; i static void findPrime(int num1, int num2) < System.out.println("List of prime numbers between " +num1+ " and " +num2+ " :"); for (int i = num1; i > > > import java.util.Scanner; public class PrimeTest < public static void main(String[] args) < // Create an object of Scanner class to connect with keyboard. Scanner sc = new Scanner(System.in); System.out.println("Enter your first number:"); int num1 = sc.nextInt(); System.out.println("Enter your second number:"); int num2 = sc.nextInt(); Primes.findPrime(num1, num2); >>Output: Enter your first number: 10 Enter your second number: 30 List of prime numbers between 10 and 30 : 11 13 17 19 23 29In this program, we have generated prime number series between two given numbers. A prime number is a number that is divisible by 1 and itself but not divisible by any other number. For example, the prime numbers between 2 and 10 are 2, 3, 5, and 7.
Hope that this tutorial has elaborated on all the important points concerning how to return array in java from a method. I hope that you will have understood the concepts of returning an array from a method in Java.
In the next tutorial, we will learn about arrays class in Java and its methods with examples. If you like this tutorial, please share it on the social sites for your friends.
Thanks for reading.Как вернуть массив из функции java
Метод - это блок кода, который выполняет определенную операцию. Он может быть вызван из других частей программы, чтобы выполнить свою функцию.
Для того, чтобы вернуть массив из метода в Java , нужно указать тип возвращаемого значения метода как тип массива. Вот пример:
public class MyClass public static int[] createArray() int[] array = new int[5]; for (int i = 0; i array.length; i++) array[i] = i; > return array; > >
Этот код создаст метод createArray() , который возвращает массив из пяти целых чисел, заполненных значениями от 0 до 4. Чтобы вызвать этот метод и получить возвращаемый массив, можно использовать следующий код:
int[] myArray = MyClass.createArray(); // [0, 1, 2, 3, 4]
Как вернуть массив из метода java
Для того, чтобы вернуть массив из метода в Java , нужно указать тип возвращаемого значения метода как тип массива. Вот пример:
public class MyClass public static int[] getNumbers() int[] array = new int[5]; for (int i = 0; i array.length; i++) array[i] = i; > return array; > >
Этот код создаст метод getNumbers() , который возвращает массив из пяти целых чисел, заполненных значениями от 0 до 4. Чтобы вызвать этот метод и получить возвращаемый массив, можно использовать следующий код:
int[] myArray = MyClass.getNumbers(); // [0, 1, 2, 3, 4]