3

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?

1
  • 1
    sniker Since all writes must firstr be reads in the java memory model this is impossible unless good old chuck norris comes about Commented Apr 16, 2013 at 0:46

6 Answers 6

3

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

0

for example you have procedure as you said:

public void sortArray(typeArray[] A){
 //code
 //code
}

calling array:

typeArray[] A = new typeArray[N]; //N is number of array you want to create
searchArray(A); //this how I call array

Comments

0

You just pass the name of the array to the method.

int[] a = new int[10];

...

bar(a);

where bar is defined like:

void bar(int[] a)
{
    ...
}

Comments

0

This way you can pass an array

int[] a = new int[100];
myFunction(a);

 public void myFunction(int[] a){
       for(int i =0; i< a.lenght();i++){

                System.out.println(i);

              }

       }

Comments

0

You can also create an anonymous array if you don't want an array to be named like:

public void array(int arr[])
{
    // code handling arr
}

Now for the above method you can pass an array object without creating it like:

public static void main(String[] args)
{
   array(int[] {1,2,3,4,5});
}

This is also named as an Un-Named Array or Anonymous array. There is no need to create an array for call by value. If you don't want that array inside the main() method anymore you can use an un-named array. This helps in memory saving. Thankyou

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.