
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
Pass Arrays to Methods in Java
You can pass arrays to a method just like normal variables. When we pass an array to a method as an argument, actually the address of the array in the memory is passed (reference). Therefore, any changes to this array in the method will affect the array.
Suppose we have two methods min() and max() which accepts an array and these methods calculates the minimum and maximum values of the given array respectively:
Example
import java.util.Scanner; public class ArraysToMethod { public int max(int [] array) { int max = 0; for(int i=0; i<array.length; i++ ) { if(array[i]>max) { max = array[i]; } } return max; } public int min(int [] array) { int min = array[0]; for(int i = 0; i<array.length; i++ ) { if(array[i]<min) { min = array[i]; } } return min; } public static void main(String args[]) { 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(); } ArraysToMethod m = new ArraysToMethod(); System.out.println("Maximum value in the array is::"+m.max(myArray)); System.out.println("Minimum value in the array is::"+m.min(myArray)); } }
Output
Enter the size of the array that is to be created :: 5 Enter the elements of the array :: 45 12 48 53 55 Maximum value in the array is ::55 Minimum value in the array is ::12
Advertisements