The Java Program: PassByReference.java

  1 // PassByReference.java -- Java uses call-by-value for references to objects and arrays
  2 
  3 class PassByReference {
  4 
  5    public static void main (String[] args) {
  6       double A [] = {1.0, 2.0};
  7       System.out.println ("before: "+A);
  8       System.out.println ("before: A[0] = " + A[0] + ", A[1] = " + A[1]);
  9       halveIt (A);
 10       System.out.println ("after: "+A);
 11       System.out.println ("after: A[0] = " + A[0] + ", A[1] = " + A[1]);
 12    }
 13 
 14    public static void halveIt (final double Z []) {
 15       for (int i=0; i<Z.length; i++) Z[i] /= 2.0;
 16       System.out.println ("halved: Z[0] = " + Z[0] + ", Z[1] = " + Z[1]);
 17 
 18       /* The assignment
 19          Z = new double [] {1.0, 4.0};
 20          is not legal because Z is declared "final"
 21 
 22          And, in any case, changing Z has no effect on A.
 23       */
 24    }
 25 }