Initializing an array - Java Language Basics

Java examples for Language Basics:Array

Description

Initializing an array

Demo Code

public class Main {
  public static void main(String[] args) {

    // get array size from first command-line argument
    int arrayLength = 5;
    int[] array = new int[arrayLength];

    // get initial value and increment from command-line arguments
    int initialValue = 1;
    int increment = 2;

    // calculate value for each array element
    for (int counter = 0; counter < array.length; counter++)
      array[counter] = initialValue + increment * counter;

    System.out.printf("%s%8s%n", "Index", "Value");

    // display array index and value
    for (int counter = 0; counter < array.length; counter++)
      System.out.printf("%5d%8d%n", counter, array[counter]);

  }//from   www.  j  a v  a 2  s. c  om
}

Result


Related Tutorials