Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass array to method Java

Tags:

java

arrays

How can I pass an entire array to a method?

private void PassArray() {     String[] arrayw = new String[4];     //populate array     PrintA(arrayw[]); }  private void PrintA(String[] a) {     //do whatever with array here } 

How do I do this correctly?

like image 599
Dacto Avatar asked Oct 23 '09 00:10

Dacto


People also ask

When you pass an array to a method How is it passed in Java?

Passing Two-dimensional Arrays to Methods in Java While calling a method with two-dimensional array parameter list, just pass array name to the method like this: object-reference. show(x); Here, object-reference is a reference to an object of underlying class and x is a two-dimensional array declared in the program.

Is it possible to pass full array to method?

You can pass an entire array, or a single element from an array, to a method. Notice that the int [ ] indicates an array parameter. Notice that passing a single array element is similar to passing any single value. Only the data stored in this single element is passed (not the entire array).

When an array is passed to a method What does the method receive?

Explanation: When sending an array to a method, the method receives the array's reference. The array reference is returned when a method returns an array. Arrays are provided to methods in the same way that regular variables are.

How are arrays passed in Java?

Everything in Java is passed by value. In case of an array (which is nothing but an Object), the array reference is passed by value (just like an object reference is passed by value). When you pass an array to other method, actually the reference to that array is copied.


2 Answers

You do this:

private void PassArray() {     String[] arrayw = new String[4]; //populate array     PrintA(arrayw); }  private void PrintA(String[] a) {     //do whatever with array here } 

Just pass it as any other variable.
In Java, arrays are passed by reference.

like image 199
NawaMan Avatar answered Sep 23 '22 08:09

NawaMan


Simply remove the brackets from your original code.

PrintA(arryw);  private void PassArray(){     String[] arrayw = new String[4];     //populate array     PrintA(arrayw); } private void PrintA(String[] a){     //do whatever with array here } 

That is all.

like image 35
jjnguy Avatar answered Sep 20 '22 08:09

jjnguy