A Java array length example

Java FAQ: How do I determine the Java array length, i.e., the length of a Java array?

Solution

While you might logically expect there to be a length method on a Java array, there is actually a public length attribute on an array (instead of a length method). Therefore, to get the Java array length, you access this array length attribute, like this:

int length = myArray.length;

A complete example

Here’s a source code example that demonstrates how to determine the Java array length for an array named toppings:

/**
 * Determine the Java array length, i.e.,
 * the length of a Java array.
 * @author https://alvinalexander.com
 *
 */
public class JavaArrayLengthExample
{

  public static void main(String[] args) {
      String[] toppings = {"cheese", "pepperoni", "black olives"};
      int arrayLength = toppings.length;
      System.out.format("The Java array length is %d", arrayLength);
  }

}

As you can see from that code, the array length is accessed from the array length attribute, like this:

int arrayLength = toppings.length;

I don't know the reasoning behind this attribute approach, but you would logically expect there to be a Java array length method, but for some reason this is a public field/attribute, and not a length method.

Note that you can shorten this Java array length example by combining those last two lines, making the example look like this:

String[] toppings = {"cheese", "pepperoni", "black olives"};
System.out.format("The Java array length is %d", toppings.length);

The approach you take just depends on whether you want to use a arrayLength variable in your code, or if you just want to access the array length attribute (toppings.length).

Either of these two Java array length approaches will print the following output:

The Java array length is 3