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 PrintA(String[] a) {
//do whatever with array here
}
How do I do this correctly?
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 []
Sample Program
import java.util.*;
class atg {
void a() {
int b[]={1,2,3,4,5,6,7};
c(b);
}
void c(int b[]) {
int e=b.length;
for(int f=0;f<e;f++) {
System.out.print(b[f]+" ");//Single Space
}
}
public static void main(String args[]) {
atg ob=new atg();
ob.a();
}
}
Output Sample Program
1 2 3 4 5 6 7