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?
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?
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.
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.
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)
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.