One Dimensional Arrays

1D Array Length

🙋 Need help? Ask an expert now!

As we stated previously, the way index works with arrays is similar to how index works with String values. Arrays also have a way of returning their own length, but in place of a method like with strings, the array's length is a variable, meaning the parenthesis are not needed. Look below to see how we can access the length of an array.
package exlcode;

public class ArrayLength1DExample {

  public static int[] exampleVariableOne = new int[5];
  public static int[] exampleVariableTwo = {0, 1, 2, 3, 4, 5, 6, 7, 8};
  // returns the length of the array and assigns
  // it to integer variables
  public static int lengthOne = exampleVariableOne.length;
  public static int lengthTwo = exampleVariableTwo.length;

  public static void main(String[] args) {

The length of an array equals the number of elements it can hold. The last index of an array is array.length-1. Remember that the length() method in the String class works differently than array.length().

The length of an array cannot be altered after it is initialized. Please remember this quality when you loop through arrays with for/while statements.

Edit Me on GitHub!

Application Question