7.4. Examples Using Arrays

This section presents several examples that demonstrate declaring arrays, creating arrays, initializing arrays and manipulating array elements.

Creating and Initializing an Array

The application of Fig. 7.2 uses keyword new to create an array of 10 int elements, which are initially zero (the default for int variables).

Figure 7.2. Initializing the elements of an array to default values of zero.
 1 // Fig. 7.2: InitArray.java
 2 // Creating an array.
 3
 4 public class InitArray
 5 {
 6    public static void main( String args[] )
 7    {
 8       int array[]; // declare array named array
 9
10       array = new int[ 10 ]; // create the space for array
11
12       System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings
13
14       // output ...

Get Java™ How to Program, Seventh Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.