Array initialization

Bruce Eckel's Thinking in Java Contents | Prev | Next

Initializing arrays in C is error-prone and tedious. C++ uses aggregate initialization to make it much safer. [22] Java has no “aggregates” like C++, since everything is an object in Java. It does have arrays, and these are supported with array initialization.

//: Arrays.java
// Arrays of primitives.
 
public class Arrays {
  public static void main(String[] args) {
    int[] a1 = { 1, 2, 3, 4, 5 };
    int[] a2;
    a2 = a1;
    for(int i = 0; i < a2.length; i++)
      a2[i]++;
    for(int i = 0; i < a1.length; i++)
      prt("a1[" + i + "] = " + a1[i]);
  }
  static void prt(String s) {
    System.out.println(s);
  }
} ///:~ 

You can see that a1 is given an initialization value while a2 is not; a2 is assigned later – in this case, to another array.

There’s something new here: all arrays have an intrinsic member (whether they’re arrays of objects or arrays of primitives) that you can query – but not change – to tell you how many elements there are in the array. This member is length. Since arrays in Java, like C and C++, start counting from element zero, the largest element you can index is length - 1 . If you go out of bounds, C and C++ quietly accept this and allow you to stomp all over your memory, which is the source of many infamous bugs. However, Java protects you against such problems by causing a run-time error (an exception, the subject of Chapter 9) if you step out of bounds. Of course, checking every array access costs time and code and there’s no way to turn it off, which means that array accesses might be a source of inefficiency in your program if they occur at a critical juncture. For Internet security and programmer productivity, the Java designers thought that this was a worthwhile tradeoff.

//: ArrayNew.java
// Creating arrays with new.
import java.util.*;
 
public class ArrayNew {
  static Random rand = new Random();
  static int pRand(int mod) {
    return Math.abs(rand.nextInt()) % mod;
  }
  public static void main(String[] args) {
    int[] a;
    a = new int[pRand(20)];
    prt("length of a = " + a.length);
    for(int i = 0; i < a.length; i++)
      prt("a[" + i + "] = " + a[i]);
  }
  static void prt(String s) {
    System.out.println(s);
  }
} ///:~ 

Since the size of the array is chosen at random (using the pRand( ) method defined earlier), it’s clear that array creation is actually happening at run-time. In addition, you’ll see from the output of this program that array elements of primitive types are automatically initialized to ”empty” values. (For numerics, this is zero, for char, it’s null, and for boolean, it's false.)

Of course, the array could also have been defined and initialized in the same statement:

int[] a = new int[pRand(20)];

If you’re dealing with an array of non-primitive objects, you must always use new. Here, the handle issue comes up again because what you create is an array of handles. Consider the wrapper type Integer, which is a class and not a primitive:

//: ArrayClassObj.java
// Creating an array of non-primitive objects.
import java.util.*;
 
public class ArrayClassObj {
  static Random rand = new Random();
  static int pRand(int mod) {
    return Math.abs(rand.nextInt()) % mod;
  }
  public static void main(String[] args) {
    Integer[] a = new Integer[pRand(20)];
    prt("length of a = " + a.length);
    for(int i = 0; i < a.length; i++) {
      a[i] = new Integer(pRand(500));
      prt("a[" + i + "] = " + a[i]);
    }
  }
  static void prt(String s) {
    System.out.println(s);
  }
} ///:~ 

Here, even after new is called to create the array:

Integer[] a = new Integer[pRand(20)];

it’s only an array of handles, and not until the handle itself is initialized by creating a new Integer object is the initialization complete:

a[i] = new Integer(pRand(500));

If you forget to create the object, however, you’ll get an exception at run-time when you try to read the empty array location.

Take a look at the formation of the String object inside the print statements. You can see that the handle to the Integer object is automatically converted to produce a String representing the value inside the object.

It’s also possible to initialize arrays of objects using the curly-brace-enclosed list. There are two forms, the first of which is the only one allowed in Java 1.0. The second (equivalent) form is allowed starting with Java 1.1:

//: ArrayInit.java
// Array initialization
 
public class ArrayInit {
  public static void main(String[] args) {
    Integer[] a = {
      new Integer(1),
      new Integer(2),
      new Integer(3),
    };
 
    // Java 1.1 only:
    Integer[] b = new Integer[] {
      new Integer(1),
      new Integer(2),
      new Integer(3),
    };
  }
} ///:~ 

This is useful at times, but it’s more limited since the size of the array is determined at compile time. The final comma in the list of initializers is optional. (This feature makes for easier maintenance of long lists.)

//: VarArgs.java
// Using the Java 1.1 array syntax to create
// variable argument lists
 
class A { int i; }
 
public class VarArgs {
  static void f(Object[] x) {
    for(int i = 0; i < x.length; i++)
      System.out.println(x[i]);
  }
  public static void main(String[] args) {
    f(new Object[] { 
        new Integer(47), new VarArgs(), 
        new Float(3.14), new Double(11.11) });
    f(new Object[] {"one", "two", "three" });
    f(new Object[] {new A(), new A(), new A()});
  }
} ///:~ 

At this point, there’s not much you can do with these unknown objects, and this program uses the automatic String conversion to do something useful with each Object. In Chapter 11 (run-time type identification or RTTI) you’ll learn how to discover the exact type of such objects so that you can do something more interesting with them.

Multidimensional arrays

//: MultiDimArray.java
// Creating multidimensional arrays.
import java.util.*;
 
public class MultiDimArray {
  static Random rand = new Random();
  static int pRand(int mod) {
    return Math.abs(rand.nextInt()) % mod;
  }
  public static void main(String[] args) {
    int[][] a1 = {
      { 1, 2, 3, },
      { 4, 5, 6, },
    };
    for(int i = 0; i < a1.length; i++)
      for(int j = 0; j < a1[i].length; j++)
        prt("a1[" + i + "][" + j +
            "] = " + a1[i][j]);
    // 3-D array with fixed length:
    int[][][] a2 = new int[2][2][4];
    for(int i = 0; i < a2.length; i++)
      for(int j = 0; j < a2[i].length; j++)
        for(int k = 0; k < a2[i][j].length;
            k++)
          prt("a2[" + i + "][" +
              j + "][" + k +
              "] = " + a2[i][j][k]);
    // 3-D array with varied-length vectors:
    int[][][] a3 = new int[pRand(7)][][];
    for(int i = 0; i < a3.length; i++) {
      a3[i] = new int[pRand(5)][];
      for(int j = 0; j < a3[i].length; j++)
        a3[i][j] = new int[pRand(5)];
    }
    for(int i = 0; i < a3.length; i++)
      for(int j = 0; j < a3[i].length; j++)
        for(int k = 0; k < a3[i][j].length;
            k++)
          prt("a3[" + i + "][" +
              j + "][" + k +
              "] = " + a3[i][j][k]);
    // Array of non-primitive objects:
    Integer[][] a4 = {
      { new Integer(1), new Integer(2)},
      { new Integer(3), new Integer(4)},
      { new Integer(5), new Integer(6)},
    };
    for(int i = 0; i < a4.length; i++)
      for(int j = 0; j < a4[i].length; j++)
        prt("a4[" + i + "][" + j +
            "] = " + a4[i][j]);
    Integer[][] a5;
    a5 = new Integer[3][];
    for(int i = 0; i < a5.length; i++) {
      a5[i] = new Integer[3];
      for(int j = 0; j < a5[i].length; j++)
        a5[i][j] = new Integer(i*j);
    }
    for(int i = 0; i < a5.length; i++)
      for(int j = 0; j < a5[i].length; j++)
        prt("a5[" + i + "][" + j +
            "] = " + a5[i][j]);
  }
  static void prt(String s) {
    System.out.println(s);
  }
} ///:~ 

The code used for printing uses length so that it doesn’t depend on fixed array sizes.

The first example shows a multidimensional array of primitives. You delimit each vector in the array with curly braces:

    int[][] a1 = {
      { 1, 2, 3, },
      { 4, 5, 6, },
    };

Each set of square brackets moves you into the next level of the array.

The second example shows a three-dimensional array allocated with new. Here, the whole array is allocated at once:

int[][][] a2 = new int[2][2][4];

But the third example shows that each vector in the arrays that make up the matrix can be of any length:

    int[][][] a3 = new int[pRand(7)][][];
    for(int i = 0; i < a3.length; i++) {
      a3[i] = new int[pRand(5)][];
      for(int j = 0; j < a3[i].length; j++)
        a3[i][j] = new int[pRand(5)];
    }

The first new creates an array with a random-length first element and the rest undetermined. The second new inside the for loop fills out the elements but leaves the third index undetermined until you hit the third new.

You will see from the output that array values are automatically initialized to zero if you don’t give them an explicit initialization value.

You can deal with arrays of non-primitive objects in a similar fashion, which is shown in the fourth example, demonstrating the ability to collect many new expressions with curly braces:

    Integer[][] a4 = {
      { new Integer(1), new Integer(2)},
      { new Integer(3), new Integer(4)},
      { new Integer(5), new Integer(6)},
    };

The fifth example shows how an array of non-primitive objects can be built up piece by piece:

    Integer[][] a5;
    a5 = new Integer[3][];
    for(int i = 0; i < a5.length; i++) {
      a5[i] = new Integer[3];
      for(int j = 0; j < a5[i].length; j++)
        a5[i][j] = new Integer(i*j);
    }

The i*j is just to put an interesting value into the Integer.


[22] See Thinking in C++ for a complete description of aggregate initialization.



Comments

  • We Offer The Low Price Jewelry Online With Good Quality 8g

    Posted by Robnek93 on 03/05/2013 07:00pm

    [p]Well is fairly opposite to the name provided to [url=http://www.airjrodan2013.com]nike air jordan retro[/url] it . It is not stunning Air Max if you remember to consider what on earth is [url=http://www.airjrodan2013.com/air-jordan-12-retro.html]Jordan 12 Retro[/url] happening . Learning them is straightforward with all the right teacher, mastering them requires work (despite the very best teacher) . When seeing nike air jordan [url=http://www.airjrodan2013.com]air jordan release dates 2013[/url] shoe, the felling of your form of extravagancesoon will come to your brains . There茅聢楼忙陋職 positively nothing very [url=http://www.2013sportsshoes.com/air-jordan-13-retro.html]Air Jordan 2012[/url] like a producer new couple of Nike茅聢楼忙陋職 . These words are accomplished at grabbing people's attention and getting these [url=http://www.2013sportsshoes.com/air-jordan-retro-1.html]Jordan Retro 1[/url] to click your link . Leather [url=http://www.airjrodan2013.com/air-jordan-5-retro.html]Jordan 5 Retro[/url] shoes are great for all occasions . 1.[/p]

    Reply
  • Consultant

    Posted by Sankar.lp.gym on 10/26/2012 12:13am

    Java supports jagged array http://wisentechnologies.com/it-courses/java-training.aspx

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: November 20, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Are you wanting to target two or more platforms such as iOS, Android, and/or Windows? You are not alone. 90% of enterprises today are targeting two or more platforms. Attend this eSeminar to discover how mobile app developers can rely on one IDE to create applications across platforms and approaches (web, native, and/or hybrid), saving time, money, and effort and introducing apps to market faster. You'll learn the trade-offs for gaining long …

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds