Example of arrays of integers:

public class Array1 {
    public static void main(String [] args) {
	int [] a = new int[5]; // declaring an array

	// initializing some elements:
	a[0] = 1;
	a[1] = 3;
	a[2] = 5;
	// the rest of elements have default values (0 for int)

	// priniting the array
	for (int i = 0; i < a.length; i++) {
	    System.out.println("a[" + i + "] = " + a[i]);
	}
    }
}



public class Array2 {
    public static void main(String [] args) {
	double [] a = {2.3, 4.1, -9.0}; // declaring and initializing array

	// priniting the array
	for (int i = 0; i < a.length; i++) {
	    System.out.println("a[" + i + "] = " + a[i]);
	}
    }
}


And another kind of a loop (for arrays only!):

// this loop is a new addition in Java 5

public class ForEach {
    public static void main(String [] args) {
	int [] arr = {5, 4, 3, 8};

	for (int item : arr) {
	    System.out.println(item);
	}

	// works exactly the same as
	for (int i = 0; i < arr.length; ++i) {
	    int item = arr[i];
	    System.out.println(item);
	}
    }
}

This is an example from CSci 2101 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.