Java Reference
In-Depth Information
//
File name: ArrayOps.java
//
Reference: Chapter 6
//
//
Java program to demonstrate arrays
//
Topics:
//
1. Simultaneous Array declaration and initialization
//
2. Use of the length operator
//
public class Arrays
{
public static void main(String[] args)
{
int[] nums = {1, 1, 2, 3, 5, 8, 13, 21};
char[] lets = {'t', 'h', 'i', 's', ' ', 'i', 's'};
System.out.print(“The value of nums[3] is ” + nums[3]);
System.out.print(“\nThe value of lets[5] is ” + lets[5]);
System.out.flush();
}
}
Multi-dimensional arrays
A Java array can have more than one dimension. Two-dimensional arrays
are often used to represent the entries in a table or other data that is orga-
nized in rows and columns. In the case of a two-dimensional array one index
represents the table rows and another one the columns. A three-dimensional
array can be used to represent a grid with breadth,width,and depth.
Suppose that you were to develop a program that keeps track of the
pieces on a game of checkers. The standard checkerboard consists of
eight columns by eight rows of cells into which the pieces can move. You
could use the letter “r” to represent the red pieces and the letter “b” for
the black pieces. Then the letter “R” would represent crowned red pieces
andtheletter“B”crownedblackpieces. Figure6-2 s howsapossibleposi-
tion of the checker pieces of a game in progress.
Since the red and black pieces are identified by letters,the program
could use a two-dimensional array of type char to represent the checker-
board. The array could be created as follows:
char[] checkerboard = new char[8][8];
Two-dimensional arrays in Java are in row-major order . This means
that the first dimension represents the array rows and the second one the
array columns. In the case of the checkerboard[] array we can store the
piece located at row number 0,column number 2 as follows:
checkerboard[0][2] = 'b';
Search WWH ::




Custom Search