Java Arrays

An array is a type of container like a variable, but instead or storing one value, an array can store a series of values. Each value the array stores is called an element of the array and must be of the same data type. So, an int array stores int values. A float array stores float values, and so on.

The number of elements an array has is called the array length and is established when the array is created. The array elements are numbered starting with 0. So, an array with a length of five elements will have elements numbered 0 – 4.

To declare an array we add [ ] brackets after the type. Let’s look at an array now:

public class MyClass {

  public static void main(String[] args) {

    int[] myIntArray = new int[5];

  }
}

Here we have declared an array of int values called ‘myIntArray.’ This array has a length of 5 elements. But we did not assign any values to our array. To initialize values to our elements we call the array by name and use [ ] brackets to indicate which element position we are accessing. Like this:

public class MyClass {

  public static void main(String[] args) {

    int[] myIntArray = new int[5];

    myIntArray[0] = 2;
    myIntArray[1] = 4;
    myIntArray[2] = 6;
    myIntArray[3] = 8;
    myIntArray[4] = 10;

  }
} 

Now that we have added values to our array elements, we can print one or use a loop to print all the elements.

public class MyClass {

  public static void main(String[] args) {

    int[] myIntArray = new int[5];

    myIntArray[0] = 2;
    myIntArray[1] = 4;
    myIntArray[2] = 6;
    myIntArray[3] = 8;
    myIntArray[4] = 10;

    //print the first element
    System.out.println(myIntArray[0]);

    //print all elements
    for(int i = 0; i < 5; i++) {
      System.out.println(myIntArray[i]);
    }

  }
}
2
2
4
6
8
10

There is also a way to declare an array and initialize its values all at once.

public class MyClass {

  public static void main(String[] args) {

    int[] myIntArray = {2, 4, 6, 8, 10};

  }
} 

Arrays have a built in property called length. A property is like a variable that belongs to an object. In this case the array’s length property stores the number of elements in a particular array. You can access it by calling (array’s name).length like this:

public class MyClass {

  public static void main(String[] args) {

    int[] myIntArray = {2, 4, 6, 8, 10};

    System.out.println(myIntArray.length);

  }
}

The output is:

5

Comments

Popular Posts