Arrays in methods

Passing arrays in methods

class jamesprogram {

	public static void main(String args[]){
		
		int james[] = {2,4,6,8};
		changearray(james);
		
		for (int y:james){
			System.out.println(y);
			
		}
	}
	
	// this method is expecting to receive an array
	public static void changearray(int x[]){
		
		for (int count=0; count<x.length;count++){
			x[count]+=5;
		}
	}
}

Outputs:

7
9
11
13

We pass our array james to the changearray method which adds 5 to each element.

Leave a Reply