Bright Java Tutorial

is brought to you by DoITBright LLC



An array is a data structure of fixed length that can store the same types in it. The length of the array is determined when the array is created. Once the length is determined, it is fixed. It can no longer increase its length nor decrease its length. Let us look at the example below.

  package com.example.core;

   * @author Rolan Liwanag
  public class ArrayExample {

    public static void main(String[] args) {
	  int[] anIntArr1 = {1,2,3};
      System.out.println("The size of anIntArr1 is " 
        + anIntArr1.length);
       * anIntArr1 is an array object containing values 
       * 1, 2, and 3 during creation.
      //an array index starts at 0. This means, to get the 
      //first entry in the array, we do, anIntArr1[0]
      //the next entry in the array will be accessed by 
      //using index equal to 1
      //and so forth
       * so, the last index of the array will be 
       * anIntArr1.length - 1. 
       * DO NOT exceed the maximum possible index because 
       * it will throw an IndexOutOfBoundsException.
       * Example: anIntArr1[3]
      int[] anIntArr2 = new int[2];
      System.out.println("The size of anIntArr2 is " 
        + anIntArr2.length);
       * anIntArr2 is an array object containing values 
       * 0 and 0. int by default is equal to 0.
       * Same concepts will apply here. 
       * DO NOT exceed the maximum possible index because 
       * it will throw an IndexOutOfBoundsException.
      //setting the value of array element after 
      //the creation of array
      anIntArr2[1] = 1;
      System.out.println("The new value of anIntArr2[1] is " 
        + anIntArr2[1]);
      //Let us try a String array
      String[] stringArr = new String[2];
      stringArr[0] = "String at index zero.";
      //Remember, we only initialized the first element.
      for(int idx = 0; idx < stringArr.length; idx++) {
       * As you may have seen, the value of the second
       * array element is 'null'. Like many objects,
       * when these are not initialized, the value will
       * be 'null'.

Back    Next