Passing arrays to methods

In Java, Arrays are Objects. Hence, they behave exactly as objects do. If the array is modified in the method then the caller will also see the updated value.

Here is an example,

package com.ibytecode.arrays;
public class PassingArrayToMethod {
	public static void main(String[] args) {
		int arr[] = {1,2,3,4,5};
		System.out.println("In main: Before Passing array to methodTest");
		for(int i=0; i<arr.length; i++)
		{
			System.out.print(arr[i] + " ");
		}
		System.out.println();
		methodTest(arr);
		System.out.println("In main: After returning from methodTest:");
		for(int i=0; i<arr.length; i++)
		{
			System.out.print(arr[i] + " ");
		}
	}
	
	public static void methodTest(int[] arrTest)
	{
		for(int i=0; i<arrTest.length; i++)
		{
			arrTest[i] += 10 ;
		}
		System.out.println("Printing Array values in methodTest");
		for(int i=0; i<arrTest.length; i++)
		{
			System.out.print(arrTest[i] + " ");
		}
		System.out.println();
		arrTest = null;
	}
}

In main: Before Passing array to methodTest
1 2 3 4 5
Printing Array values in methodTest
11 12 13 14 15
In main: After returning from methodTest:
11 12 13 14 15

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.