HIDE NAV

Array Basics

The below command line program demonstrates the basics of array declaration and access.
This code also show the common loop style counting upward from zero through all array indices that is frequently used to initialize or access an array.

Main.java


package ceccs;

public class Main {

    public static void main(String[] args) {
        int size = 10;

        // create an array of double type, size = 10
        // variables are:  values[0]  ... values[9]
        double[] values;
        values = new double[size];
        
        // assignment and access of a single variable - fourth variable
        values[3] = -27.3;
        System.out.println("the value of v[3] is " + values[3]);

        System.out.println("------------------------------");

        // assignment of all array variables in while loop
        int n = 0;
        while (n < size) {
            values[n] = Math.pow(2,n);
            n++;
        }        
        // accessing array variables in a while loop
        n = 0;
        while (n < size){
            System.out.println("the value of v[" + n + "]" + "is " + values[n]);
            n++;
        }

        System.out.println("------------------------------");

        //assignment of all array members in for loop
        for (int i = 0; i < size; i++){
            values[i] = Math.pow(3,i);
        }
        // accessing variables in a for loop
        for (int i = 0; i < size; i++){
            System.out.println("the value of v[" + i + "]"+ "is " + values[i]);
        }
    }
}