The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Object Basics and Simple Data Objects

Arrays of Arrays

Arrays can contain arrays. ArrayOfArraysDemo(in a .java source file) creates an array and uses an initializer to populate it with four sub-arrays.
public class ArrayOfArraysDemo {
    public static void main(String[] args) {
        String[][] cartoons =
        {
	    { "Flintstones", "Fred", "Wilma", "Pebbles", "Dino" },
            { "Rubbles", "Barney", "Betty", "Bam Bam" },
            { "Jetsons", "George", "Jane", "Elroy", "Judy", "Rosie", "Astro" },
            { "Scooby Doo Gang", "Scooby Doo", "Shaggy", "Velma", "Fred", "Daphne" }
        };

        for (int i = 0; i < cartoons.length; i++) {
	    System.out.print(cartoons[i][0] + ": ");
            for (int j = 1; j < cartoons[i].length; j++) {
	        System.out.print(cartoons[i][j] + " ");
	    }
	    System.out.println();
        }
    }
}
Notice that the sub-arrays are all of different lengths. The names of the sub-arrays are cartoons[0], cartoons[1], and so on.

As with arrays of objects, you must explicitly create the sub-arrays within an array. So if you don't use an initializer, you need to write code like the following, which you can find in: ArrayOfArraysDemo2(in a .java source file)

public class ArrayOfArraysDemo2 {
    public static void main(String[] args) {
        int[][] aMatrix = new int[4][];

	//populate matrix
        for (int i = 0; i < aMatrix.length; i++) {
	    aMatrix[i] = new int[5];	//create sub-array
	    for (int j = 0; j < aMatrix[i].length; j++) {
	        aMatrix[i][j] = i + j;
	    }
        }

        //print matrix
        for (int i = 0; i < aMatrix.length; i++) {
	    for (int j = 0; j < aMatrix[i].length; j++) {
	        System.out.print(aMatrix[i][j] + " ");
	    }
	    System.out.println();
        }
    }
}
You must specify the length of the primary array when you create the array. You can leave the length of the sub-arrays unspecified until you create them.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2002 Sun Microsystems, Inc. All rights reserved.