Java Programming/Arrays

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search
Navigation Left Arrow.svg Classes, Objects and Types Java Programming
Arrays
Flow control Navigation Right Arrow.svg


Navigate Language Fundamentals topic: ( v d e )

Contents

[edit] Intro to Arrays

An array is similar to a table of data, keyed by number. In Java an array is an object like all other objects. Look at the following program:

import java.util.*;
 
public class ArrayExample {
	static Scanner input = new Scanner(System.in);
 
	public static void main(String[] args) {
		int numNames = getInt("Number of names?");
		String[] names = new String[numNames];
		for (int i = 0; i < names.length; i++) {
			names[i] = getString("Enter name #" + i);
		}
		for (int i = 0; i < names.length; ++i) {
			System.out.println(names[i]);
		}
	}
 
	public static int getInt(String prompt) {
		System.out.print(prompt + " ");
		int integer = input.nextInt();
		input.nextLine(); // Get rid of this line
                // so that getString won't read it
		return integer;
	}
 
	public static String getString(String prompt) {
		System.out.print(prompt + " ");
		return input.nextLine();
	}
}

Copy the code and compile it. The program will ask you to enter some names then reprints the names in order. It demonstrates three major aspects of arrays: how to define an array, how to set data, and how to access it. The code String[] names = new String[numNames]; tells Java to create an array of size numNames that will store Strings. To set data, use names[x] = data where x is the index to access. Note that all Java arrays start at 0 and go to (array size - 1). Thus, if you dimension an array to size 10, the highest index is 9.

[edit] Array Fundamentals

  • To create an array, use the syntax DataType[] variable = new DataType[ArraySize]. Alternatively, if you know the data beforehand, you can write DataType[] variable = {item 1, item 2,...item n}
    • All elements of the array will be automatically initialized with the default value for that datatype. This is false for boolean's, 0 for all numeric primitive types, and null for all reference types. So for example, the previous note created an array of DataType references, all of which are initialized to null.
  • To access an item, use the syntax variable[i] where i is the index
  • To set an item, use the syntax variable[i] = data
  • To find the length of an array, use the syntax variable.length

[edit] Two-Dimensional Arrays

A two dimensional array is represented by an array of an array. Because an array is also an object, like any other object having the Object as the super class, it can be used to create an array where the element of the array is also an array. In this way an array with any number of dimensions can be created. Here are examples of two dimensional arrays with initializer blocks:

String [][] twoDimArray = { {"00", "01", "02", "03", "04"},
                            {"10", "11", "12", "13", "14"},
                            {"20", "21", "22", "23", "23"} };
...
int [][] twoDimIntArray =  { {00, 01, 02, 03, 04},
                             {10, 11, 12, 13, 14},
                             {20, 21, 22, 23, 24} };

Note that the above "twoDimArray" is equivalent to the following more verbose code:

String [][] twoDimArray = new String[3][];
for (int i = 0; i < twoDimArray.length; i++) {
    twoDimArray[i] = new String[5];
    for (int j = 0; j < twoDimArray[i].length; j++)
        twoDimArray[i][j] = "" + i + j;
}

In the above example we defined an array which has three elements, each element contains an array having 5 elements. We could create the array having the 5 elements first and use that one in the initialize block.

String [] oneDimArray = {"00", "01", "02", "03", "04"};
String [][] twoDimArray = { oneDimArray ,
                            {"10", "11", "12", "13", "14"},
                            {"20", "21", "22", "23", "24"} };

Since they are arrays of array references, these multi-dimensional arrays can be "jagged" (i.e. subarrays can have different lenghts), or the subarray reference can even be null. Consider

String [][] weirdTwoDimArray = { {"10", "11", "12"},
                            null,
                            {"20", "21", "22", "23", "24"} };

[edit] Multidimensional Array

Going further any number of dimensional array can be defined.

<elementType>[][]...[] <arrayName>
or
<elementType><arrayName>[][]...[]


Java Programming Index
Overview   Getting Started   Fundamentals   Classes and Objects  
Collections   Exceptions   Concurrent Programming   Reflection
Applets   JavaBeans Libraries