Methods Returning Object References

  1. A method can "create" (reserve space) an object and then later return the reference (address) of the newly created object

    Since an array is an object, we can therefore return reference (address) of an array object

    We can use this "feature" to allow a method return multiple values.

    Example: Method returning an array object
        public class Util
        {
           // Find Max & Min value in an array
           public static int[] findMaxMin(int[] A)
           {
    	  int i;
    	  int max, min;
    
    	  max = A[0];
    	  min = A[0];
    	  for (i = 1; i < A.length; i++)
    	  {  if ( A[i] > max )
    	        max = A[i];
    
    	     if ( A[i] < min )
    		min = A[i];
    	  }
    
    	  int r[] = new int[2];  // 2 element int array    
    	  r[0] = max;
    	  r[1] = min;
    	  return(r);
           }
        }
    
    
        public class myProgram
        {
           public static void main(String[] args)     
           {
    	  int[] A = new int[10];
    	  int result[];
    	  ...
    	  result = Util.findMaxMin(A);
    	  System.out.println("Max = " + result[0]);
    	  System.out.println("Min = " + result[1]);
           }
        }
    
    

    Pictorially:

  2. DEMO programs: