A Java array length example

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

Answer: 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 just have to access this array length attribute.

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 alvin alexander, devdaily.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

Thanks for the clear explanation

Now i truely understood about array length !!!

Post new comment

The content of this field is kept private and will not be shown publicly.