tags:

views:

206

answers:

4

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?

+3  A: 

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.

jjnguy
Oh. I feel stupid now because on my program it wasnt initialized...
Dacto
Heh, I think we've all done that before. What I'd like to know is why we still have to initialize our objects explicitly. Is there any situation where we WANT a typed null pointer? Even if so, it's definitely an exception rather than the norm.
Daniel T.
A: 

An array variable is simply a pointer, so you just pass it like so:

PrintA(arrayw);

Edit:

A little more elaboration. If what you want to do is create a COPY of an array, you'll have to pass the array into the method and then manually create a copy there (not sure if Java has something like Array.CopyOf()). Otherwise, you'll be passing around a REFERENCE of the array, so if you change any values of the elements in it, it will be changed for other methods as well.

Daniel T.
A: 

You got a syntax wrong. Just pass in array's name. BTW - it's good idea to read some common formatting stuff too, for example in Java methods should start with lowercase letter (it's not an error it's convention)

DroidIn.net
Yea i was just in a hurry :)
Dacto
+3  A: 

You do this:

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

private void PrintA(String[] a){
    //do whatever with array here
}

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

NawaMan