Pass Array to Method Java
How Can I Pass an Entire Array to a Method? Private Void Passarray() { String[] Arrayw = New String[4]; //Populate Array Printa(Arrayw[]); } Private Void...
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?
10 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.
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.
Important Points
- you have to use java.util package
- array can be passed by reference
In the method calling statement
- Don't use any object to pass an array
- only the array's name is used, don't use datatype or array brackets []