Array as Parameter to a Method

  1. Knowing that an array in Java is an object, and knowing that Java always passes parameters by VALUE:

    Example: Passing an array as parameter
        public class Util
        {
           // Find Max value in an array
           public static int findMax(int[] A)
           {
    	  int i;
    	  int max;
    
    	  max = A[0];
    	  for (i = 1; i < A.length; i++)
    	     if ( A[i] > max )
    	        max = A[i];
    
    	  return(max);
           }
        }
    
    
        public class myProgram
        {
           public static void main(String[] args)     
           {
    	  int[] A = new int[10];
    	  int max;
    	  ...
    	  max = Util.findMax(A);
           }
        }
    
    

    Pictorially:

  2. Therefore:

    
        public class Util
        {
           // Add 10 to each element in array
           public static void addOne(int[] A)
           {
    	  int i;
    
    	  for (i = 0; i < A.length; i++)
    	     A[i] = A[i] + 10;
           }
        }
    
    
        public class myProgram
        {
           public static void main(String[] args)    
           {
    	  int[] A = new int[10];
    	  int i;
    
    	  for (i = 0; i < A.length; i++)
    	     A[i] = i;
                 // A[0] = 0, A[1] = 1, etc
    
    	  Util.addOne(A);
    
    	  for (i = 0; i < A.length; i++)
    	     System.out.println(A[i]);
                 // Will print: 10, 11, 12, etc
           }
        }