Array method parameters java

Passing Arrays to Methods in Java

Just as you can pass primitive type values to methods, you can also pass arrays to a method. To pass an array to a method, specify the name of the array without any square brackets within the method call. Unlike C/C++, in Java every array object knows its own length using its length field, therefore while passing array’s object reference into a method, we do not need to pass the array length as an additional argument. For example: Suppose we have an integer array num containing 10 elements.

int[] num = new int[10];

Then the method call will look like, modify (num);

As array reference is passed to the method so the corresponding parameter in the called method header must be of array type. The method body in our example will be

It indicates that the method modify receives the reference of an integer array (in our case num) in parameter x when it is being called. So if parameter x is being used in its body then actually it is referencing an array object num in the calling method.

Recall that when you pass a variable of primitive type as an argument to a method, the method actually gets a copy of value stored in the variable. So when an individual array element of primitive type is passed, the matching parameter receives a copy. However, when an array is passed as an argument, you just pass the array’s reference in matching parameter and not the copy of individual elements. Any modification made in the array using its reference will be visible to the caller.

class sortNumbers 

public static void main(String[] args)

int[] data=;
System.out.println("Unsorted List is :");
display(data);
sort(data);
System.out.println("\nSorted List is :");
display(data);
>
static void display(int num[])

for(int i=0; i
System.out.print(num[i] + " ");
>
static void sort(int num[])

int i, j, temp;
for(i=0; i

for(j=0; j

if(num[j]>num[j+1])

temp = num[j];
num[j] = num[j+1];
num[j+1] = temp;
>
>
>
>
>

Passing Arrays to Methods in Java

In this example, we sort the numbers by using the concept of passing arrays to methods. The unsorted array is passed to the sort () method. In the method’s definition, the array referenced using num reference variable is sorted and the changes made are reflected back.

You’ll also like:

Источник

How to 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; imax) < max = array[i]; >> return max; > public int min(int [] array) < int min = array[0]; for(int i = 0; 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; iArraysToMethod 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

Samual Sam

Learning faster. Every day.

Источник

Passing Arrays to Methods in Java

Scientech Easy

it is also possible to pass arrays and individual array elements as arguments to methods and returns arrays from methods.

When we pass an array argument to a method in java, actually, the reference of the array is passed to the method, not value.

Once an array is passed as an argument to a method, all elements of the array can be accessed by statements of the method.

In this tutorial, we will learn how to pass one-dimensional and multidimensional arrays as arguments to methods in java with example programs. So, let’s understand them one by one.

Passing One-dimensional Array as Arguments to Method in Java

A method that will take an array reference through a method call, method’s parameter list must define an array parameter. The general syntax to declare a method with parameter list one dimensional array is as follows:

data-type method-name(data-type array_name[ ]) < // statements >For example: void display(int num[ ]) < // statements >

Here, the presence of a pair of square brackets after the array name indicates we are passing an array.

After a method is defined, while calling it, we need to pass the array name of actual array as an argument to a method. To pass an array as an argument to a method, specify the name of array without any brackets.

The general syntax to call a method with passing an array reference is as follows:

For example, if array num is declared as:

Here, we are passing the reference of the array num to a method m1(). When we pass the reference of an array object into a method, we do not need to pass array length as an additional argument.

We can also pass an anonymous array as an argument to a method while calling the method. The general syntax to calling a method with passing an anonymous array as an argument is as follows:

method-name(new data-type[ ]); For example: m1(new int[ ]); // Here, m1 is method name.

Let’s take a simple example program in which we will display elements of one dimensional array.

Program code:

package arraysProgram; public class OneDArray < void show(int x[ ]) < for(int i = 0; i < x.length; i++) < System.out.print(x[i]+ " "); >> > public class OneDArraytoMethod < public static void main(String[ ] args) < // Declare an array x with initialization. int[ ] x = ; // Create an object of class OneDArray. OneDArray obj = new OneDArray(); System.out.println("Value of array x: "); obj.show(x); // Calling show() method with passing 1D array. > >
Output: Value of array x: 2 3 4 5 6 7 8

In this program, we have defined a class OneDArray with a method named show(). The method show() accepts a one-dimensional array as an argument and does not return any value. The purpose of show() method is to print elements of one dimensional array passed to it.

In the main method, one dimensional array x is defined with the initialization of elements. obj.show(x); calls show() method with passing 1D array x and display elements of array on the console.

Arrays are passed by reference in Java, not pass by value

We know that Java uses pass-by-value (also called call-by-value) to pass arguments to a method. But there is an important difference between passing the values of variables of primitive data types and passing arrays. They are:

1. When an argument of any primitive type (boolean, char, byte, short, int, long, float, or double) is passed to a method, the argument’s value is passed. It means that if we make a change to a value passed to a method, the original value is not affected.

2. In Java, Arrays are objects. An object actually holds a memory address where the values are stored. When an argument of an array type is passed to a method, the value of an argument is actually the reference to an array that contains a copy of the memory address where values are stored.

Therefore, we can say that entire arrays are passed by reference, not value. It simply means that if we make a change to an array passed to a method, the original array is also affected.

Let’s understand this concept with the help of a simple example program. Concentrate on the source code to understand better.

Program code:

package arraysProgram; public class PassingArrays < public static void main(String[] args) < int x = 2; // Original value. int[ ] num = ; // Original array. m1(x, num); System.out.println("Value of x: " +x); System.out.println("Value of num[1]: " +num[1]); > public static void m1(int x, int[ ] num) < x = 5; // Modifying value of x. num[1] = 20; // Modifying array. >>
Output: Value of x: 2 Value of num[1]: 20

As you can observe in the output, the value of x is the same but the values of the array are changed when modified inside the method.

Thus, if we change the array in the method, we will also see the change outside the method. Look at the figure below to understand more.

Passing arrays to methods in Java

a) In Java, arrays are objects. JVM stores objects in the heap memory, which is used for dynamic memory allocation. In simple words, arrays are stored in the heap memory.

b) In some Java books, there is also written that an array is not passed by reference, but a reference to an array is passed by value.

c) When an individual array element as an argument is passed to a method, the called method gets a copy of element’s value. It means that Java uses pass by value to pass an individual array element as an argument to a method.

So, if we make a change to the value of individual array element passed to a method, the original array element is not affected.

Let’s take an example program based on this concept. Concentrate on the below source code to understand better.

Program code:

package arraysProgram; public class PassingArrays < public static void main(String[] args) < int[ ] num = ; // Original array. m1(num[0], num[1]); // Here, passing individual array elements (by pass by value mechanism). System.out.println("Value of num[0]: " +num[0]); System.out.println("Value of num[1]: " +num[1]); > public static void m1(int x, int y) < // Modifying values of array elements. x = 5; y = 20; >>
Output: Value of num[0]: 2 Value of num[1]: 4

Let’s create a program in which we will demonstrate the difference between passing an entire array and passing array element of primitive data type to a method.

Program code:

package arraysProgram; public class PassingArrays < public static void modifyArray(int[ ] num) < for(int i = 0; i < num.length; i++) num[i] *= 2; >public static void modifyingArrayElement(int arrayElement) < arrayElement *= 5; System.out.println("\nValue of arrayElement after modifying: " +arrayElement); >public static void main(String[] args) < int[ ] num = ; System.out.println("Effect of passing reference to entire array:"); System.out.println("Original array: "); // Displaying elements of original array. for(int values : num) System.out.printf(" %d", values); modifyArray(num); // Passing array reference. System.out.println("\nModified array: "); // Displaying modified array elements. for(int values : num) < System.out.printf(" %d", values); >System.out.println("\n\nEffect of passing an element of array:"); System.out.printf("num[3] before modifying: " +num[3]); modifyingArrayElement(num[3]); // Attempt to modify num[3]. System.out.println("num[3] after modifying: " +num[3]); > >
Output: Effect of passing reference to entire array: Original array: 10 20 30 40 50 Modified array: 20 40 60 80 100 Effect of passing an element of array: num[3] before modifying: 80 Value of arrayElement after modifying: 400 num[3] after modifying: 80

Remember that when an individual primitive type array element is passed to a method, modifying the value of array element inside the called method does not affect the original value of that element in the calling method’s array.

Passing Two-dimensional Arrays to Methods in Java

For a method to take a two dimensional array as its argument, we must specify two dimensional array name followed by two pairs of square brackets preceded by the data type of array.

The general syntax of method definition is as follows:

data-type method-name(data-type array[ ][ ]) < // local variables // statements >For example: void show(int x[ ][ ]) < // local variables // statements >

While calling a method with two-dimensional array parameter list, just pass array name to the method like this:

Here, object-reference is a reference to an object of underlying class and x is a two-dimensional array declared in the program.

Let’s create a Java program in which we will display elements of a matrix.

Program code:

package arraysProgram; public class TwoDArray < void show(int x[ ][ ]) < int i, j; System.out.println("Matrix x: "); for(i = 0; i < x.length; i++) < for(j = 0; j < x.length; j++) System.out.print(x[i][j]+ " "); System.out.println(); >> > public class PassingTwoDArrayToMethod < public static void main(String[] args) < int x[ ][ ] = ,>; TwoDArray obj = new TwoDArray(); obj.show(x); > >

In this program, the show() method is designed to accept a two-dimensional array as its argument and does not return value.

The purpose of this method is to print elements of two-dimensional array passed to it. The statement obj.show(x); displays the elements of two dimensional array on the console.

Hope that this tutorial has covered almost all the important points related to passing arrays to methods in java with example programs. I hope that you will have understood how to pass one-dimensional and two-dimensional arrays to a method in java.
Thanks for reading.
Next ⇒ How to Return Array in Java ⇐ Prev Next ⇒

Источник

Читайте также:  Как поставить на фон картинку в HTML
Оцените статью