Title: Array Initializations, Parameters
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

Array Initializations, Parameters

1. When you first create arrays, you will have defaults filled in

public class Test
{
    public static void main(String[] args) {

          int[] intArr= new int[3]; // initial values of 0
          // Same thing applies for short, long, byte
          char[] charArr = new char[3]; // initial values of (char)0 --- unprintable
          boolean[] boolArr = new boolean[3]; // initial values of false
          double[] dblArr = new double[3]; // initial values of 0.0
          // same for float
          String[] strArr = new String[3];  // initial values of null

          for (int i=0; i < 3; i++)
          {
             System.out.println("i=" + i);
             System.out.println("intArr=" + intArr[i]);
             System.out.println("charArr="+ charArr[i]);
             System.out.println("boolArr=" + boolArr[i]);
             System.out.println("dblArr=" + dblArr[i]);
             System.out.println("strArr="+ strArr[i]);
             System.out.println("*****************************************");
          }
    }
}


2. Again note that having initialized arrays of classes doesn't mean that the classes are ready to go. Consider the following potential error


  Date[] holidayList = new Date[5];  // Initialized to all nulls
  holidayList[0].setMonth(1); // This statement will get an exception


3. Proper way to initialize an array of class:


  Date[] holidayList = new Date[5];
  for (int i=0; i < holidayList.length; i++)
      holidayList[i] = new Date();  // No longer a null

  holidayList[0].setMonth(1); // This works fine


4. Arrays can also be initialized and allocated as follows:

public class Test {

    public static void main(String[] args) {
         int[] age = {2, 12, 1 };
          /* This is equivalent to:
          int[] age= new int[3];
          age[0]= 2;
          age[1] = 12;
          age[2] = 1;
          */

          char[] vowels= {'a', 'e', 'i', 'o', 'u'};
          /* This is equivalent to
          char[] vowels = new char[5];
          vowels[0] = 'a';
          vowels[1] = 'e';
          vowels[2] = 'i';
          vowels[3] = 'o';
          vowels[4] = 'u';
           */

          double[] d= {1.2, 3.4, 5.6};
          /* Equalivalent to:
          double[] d = new double[3];
          d[0] = 1.2;
          d[1] = 3.4;
          d[2] = 5.6;
           */

          /*
           Remember when we started we had the issue with
           double d3 = 5.6;
           float f3 = d3; // This was a compile error ... why?
           //It was fixed with:
           f3 = (float)d3;
           //or
           f3 = 5.6f;
           */

 // unfortunately you have to do the following for floats

          float[] f = {1.2f, 3.4f, 5.6f};
          /*
          The above is equivalent to:
          float[] f = new float[3];
          f[0] = 1.2f;
          f[1] = 3.4f;
          f[2] = 5.6f;
           */
          // or
          float[] f2 ={(float)1.2, (float)3.4, (float)5.6};

          String[] s = {"she", "sells", "sea", "shells"};
          /*
          The above is equivalent to:
          String[] s = new String[4];
          s[0] = "she";
          s[1] = "sells";
          s[2] = "sea";
          s[3] = "shells";
           */

          // It's not as nice for other classes other than the String.
          // For example let's look at the Date class:

          // First the non-shortcut version:
          Date[] darr = new Date[3];
          darr[0] = new Date(1,1,2011);
          darr[1] = new Date(2,2, 2012);
          darr[2] = new Date(3,3, 2013);

          // The so called short cut version would be:
          Date[] darr2 = {new Date(1,1,2011),
                  new Date(2,2, 2012), new Date(3,3, 2013)};

          // Another way is to have the user's enter in the Dates:
          Date[] darr3 = new Date[3];
          for (int i=0; i < darr.length; i++)
          {
              darr3[i] = new Date();
              darr3[i].readInput();
          }
        }
    }



5. Note that an array of char is similar but not the same as a String. Consider:

public class Test {


    public static void main(String[] args) {
        char[] a = {'A', ' ', 'B', 'i', 'g', ' ', 'H', 'i', '!'};
          // is different than
          String s = "A Big Hi!";

         // But they look the same when printed
          System.out.println(a);
          System.out.println(s);

          // You can't do:
          s = a; // compile error because of type mismatch.
          // However, the String class provides constructors that are useful in doing useful conversion
          s = new String(a); // Works.

          System.out.println("****  Again **** ");
          System.out.println(a);
          System.out.println(s);

        }
    }



6. Passing Parameters to functions

class Data
{
    int z=1;
    Data(int z)
    {
        this.z = z;
    }
}

public class Test {

    void methodPrimitives( int x)
      {
          x = 100;
      }
      void methodArrays(int[] arrParm)
      {
          for (int i=0; i < arrParm.length; i++)
              arrParm[i] = 100+i;
      }
      void methodMutableClass(Data d)  // mutable class
      {
          d.z=100;
      }
      void methodImmutableClass(String s) // immutable class
      {
          s="changed value";
      }

    public static void main(String[] args) {
        int primitive = 1;
        Data mutableClass = new Data(1);
        int[] arr= {1,2,3};
        String immutableClass = "My First Value";

        Test t= new Test();
        t.methodPrimitives(primitive);
        t.methodArrays(arr);
        t.methodMutableClass(mutableClass);
        t.methodImmutableClass(immutableClass);

        System.out.println("primitive="+ primitive);

        System.out.println("arr=");
        for(int i=0; i < arr.length; i++)
            System.out.println(arr[i]);

        System.out.println("mutableClass=" + mutableClass.z);

        System.out.println("immutableClass=" + immutableClass);

        }
    }



  - primitives: (int, long, short, byte, char, double, float, boolean): Primitives contain values and the values are copied into the the called method .... bottom line method can't change primitives
  - Mutable classes(normal classes such as Date, Rectangle, etc.) - Class variables contain addresses. The addresses are copied into the called method. However, when a called method has an address, it can change the contents of the class through the address.
  - Arrays are also addresses, so passing an array to a method is similar to Mutable classes. If a method has an array address, it can change the contents of the array through the address.
  - Immutable classes (String, Wrapper classes such as Integer, Double, Character, Boolean, Long, Float, Short, Byte). In this cases address are passed into the method. However, an Immutable class is designed such that once it is constructed there are NO METHODS to CHANGE its contents. So whatever you see that appears to change contents ends up creating new instances of the Immutable classs. An immutable class cannot be changed by a method.
7. What do you think happens if I pass a method an array of mutable classes ... an array of Date - what do you think?
8. What do you think happens if I pass a method an array of immutable classes ... an array of String. This one is trickier.



     void methodArrayOfImmutable(String[] arr)
     {
         for (int i=0; i < arr.length; i++)
         {
             arr[i] = "Changed: " + arr[i];
         }
     }

// Add the following to main:
     String[] arrImmutable = {"a", "big", "bat"};
     t.methodArrayOfImmutable(arrImmutable);
     System.out.println("arrImmutable=");
     for (int i=0; i < arrImmutable.length; i++)
     {
         System.out.println(arrImmutable[i]);
     }


Last Modified: September 28, 2013 5:15 PM