Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to return an array from a method in Java?
We can return an array in Java from a method in Java. Here we have a method createArray() from which we create an array dynamically by taking values from the user and return the created array.
Example
import java.util.Arrays;
import java.util.Scanner;
public class ReturningAnArray {
public int[] createArray() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array that is to be created:: ");
int size = sc.nextInt();
int[] myArray = new int[size];
System.out.println("Enter the elements of the array ::");
for(int i=0; i<size; i++) {
myArray[i] = sc.nextInt();
}
return myArray;
}
public static void main(String args[]) {
ReturningAnArray obj = new ReturningAnArray();
int arr[] = obj.createArray();
System.out.println("Array created is :: "+Arrays.toString(arr));
}
}
Output
Enter the size of the array that is to be created:: 5 Enter the elements of the array :: 23 47 46 58 10 Array created is :: [23, 47, 46, 58, 10]
Advertisements