Working With Arrays

Contact Us or call 1-877-932-8228
Working With Arrays

Working With Arrays

Array elements are accessed through the array reference, by their array index:

  • The index is the element number, placed within brackets.
  • Elements are numbered from 0 to one less than the specified size.
String[] names = new String[3];

The valid elements are 0, 1, and 2, as in:

names[0] = "Sam";
names[1] = "Sue";
names[2] = "Mary";

You could access array elements in a for loop with:

for (int i = 0; i < 3; i++) System.out.println(names[i]);

Or, better programming practice would be to use the length property:

for (int i = 0; i < names.length; i++) System.out.println(names[i]);

The compiler does not check to ensure that you stay within the bounds of the array, but the JVM does check at runtime - if you try to exceed the bounds of the array, an exception will occur.

Note that a zero-length array is valid:

Book[] titles = new Book[] { };
Book[] moreTitles = new Book[0];

You might create a zero-length array as the return value from a method typed as returning an array, when there are no items to return (as opposed to returning null).

Code Sample:

import java.util.*;
public class Arrays1 {
  public static void main(String[] args) {
    Random r = new Random();
    int[] nums = new int[10];
    for (int i = 0; i < nums.length; i++) {
      nums[i] = r.nextInt(100);
    System.out.println("Element 7 is: " + nums[7]);
    String[] names = new String[3];
    names[0] = "Joe";
    names[1] = "Jane";
    names[2] = "Herkimer";
    for (int i = 0; i < names.length; i++) {
    //this line should throw an exception