Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass an array object in a parameter

I am new to java, I would like to know, how can we pass an array object as a parameter to a method.Lets say if I have:

public void sortArray(A[7])

What should I put in between the parenthesis? Should it be A[length of array] or what?

like image 853
Mfali11 Avatar asked Aug 15 '26 21:08

Mfali11


2 Answers

When you pass an array as a parameter its length and what's stored in it gets passed so you don't need to specifically specify the length. For implementation, see the example below:

Simple example of a method that takes in an int array as a parameter:

public void takeArray(int[] myArray) {
    for (int i = 0; i < myArray.length; i++) { // shows that the length can be extracted from the passed in array.
        // do stuff
    }
}

You would call this method thusly:

Say you have an array like so:

int[] someArray = {1, 2, 3, 4, 5};

Then you call the above method with:

takeArray(someArray);
like image 83
Nico Avatar answered Aug 17 '26 10:08

Nico


Just pass the array to the method. You no need to mention any size.

void sortArray(int[] array) {
  // Code
}

// To call the method and pass this array do.

int[] array = new int[10];
sortArray(array);
like image 41
Amarnath Avatar answered Aug 17 '26 11:08

Amarnath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!