Java

Find Length of Java Array

The Java array has a fixed length. It cannot grow or shrink in length. After the Java array has been initialized, its length cannot be changed. A Java array declared with a length number is automatically initialized with the default value type. If the array is declared with undefined length and no initialization, Java allows the programmer to give the array a length later in the program. Once the length is given, it cannot be changed.

Java array also has the length property, which would return the array’s length. This article illustrates the different ways in which the length of the Java array can be determined. It also shows how to iterate through the Java array, using the length property.

Remember that the Java array is obtained from the Object class. Using the array object in the normal way does not involve the importation of the Object or Array class into the program.

Declaration with Undefined Length, without Initialization

The following statement declares an array of characters, with undefined length and without initialization:

char[] arr;

This array can be given a length later, as in the following code segment:

char[] arr;

arr = new char[10];

This length of 10 remains throughout the program. The array is now initialized with default values, of which, in the case of chars, the empty character” is the default value. Each empty character in this array would be replaced by the desired char by the programmer. Empty character means no character; it is not the space character.

Declaration with Defined Length, with Default Initialization

The following single statement shows how an array of chars, defined length, and default initialization, can be declared:

char[] arr = new char[10];

Here, “new” is an operator. Note where and how the length 10 has been typed. All primitive types can be declared in this way. Reference types can be declared in this way, too. A good example of the reference type is the String class. The following declaration works fine:

String[] arr = new String[10];

Note that the type is coded in two places: on the left of the assignment operator, at a particular position, and on the assignment operator’s right-hand side.

The default value for the string is the null value. The value of 10 in either case above remains until the end of the program. Each null in the array would simply be replaced by a string object (literal), later, by the programmer.

Assigning to Array with Default Values

After creating an array with default values, the practical values can be assign to array elements, to replace the default values, as in the following program:

    public class TheClass {
        public static void main(String[] args) {
char[] arr = new char[5];
arr[0] = 'A'; arr[1] = 'B'; arr[3] = 'D'; arr[4] = 'E';
for(int i=0; i<5; i++) {System.out.print(arr[i]); System.out.print(' ');};
System.out.println();
        }
    }

The output is:

A B D E

Notice that in this program, nothing has been imported. The default value of any element that was not assigned remains the default value.

Length at Initialization

There are two ways of declaring an array with initialization. One way is as follows:

char[] arr = {'A', 'B', 'C', 'D', 'E'};

The right-hand side of this statement is the array literal. In this case, the array literal is assigned to the array at declaration. Any default element should be typed literally, as in the following statement:

char[] arr = {'A', 'B', '', 'D', 'E'};

The third value is the empty character. If the array were of a reference type, the default value would have been null, as in the following statement:

String[] arr = {"one", "two", null, "four", "five"};

Null is without quotes here. For these three statements, the length is 5, which is the number of elements in the array literal. The array literal is delimited by braces.

The other way is as follows:

char[] arr = new char[]{'A', 'B', 'C', 'D', 'E'};

Here, the new operator is used, still without the number for length. In this case, the array literal is just after the square brackets. Any default element should be typed literally, as in the following statement:

char[] arr = new char[]{'A', 'B', '', 'D', 'E'};

If the array were of a reference type, the default value would have been null, as in the following statement:

String[] arr = new String[]{"one", "two", null, "four", "five"};

null is without quotes. If null is in quotes, it is no longer null but a string. For these three statements, the length is 5, which is the number of elements in the array literal.

In array declaration with practical initialization, the number of elements in the array literal is the length of the array. That length stays till the end of the program.

The length Property

An array is an object inherited from the Object class. It has a property, which is length. As long as the length of the array has been defined, this property will always return that same fixed length of the array until the end of the program. The following code segment illustrates how to use the length property:

char[] arr = {'A', 'B', 'C', 'D', 'E'};

int len = arr.length;

System.out.println(len);

The output is: 5.

Iterating all through the Array

The following code iterates all through the array. The length property can be used to iterate, all through the array, as this program shows:

    public class TheClass {
        public static void main(String[] args) {
String[] arr = {"one", "two", "three", "four", "five"};
            for (int i=0; i<arr.length; i++) {
System.out.print(arr[i]); System.out.print(' ');
            }
System.out.println();
        }
    }

The output is:

one two three four five

The string class does not need to be imported before being used.

Normal Search for a Value

The following class looks for the character, ‘D’, in an array of characters. When the first ‘D’ is seen, the array index is returned. If the end of the array is reached, the length of the array is returned.

    class AClass {
        int simpleSearch() {
char[] arr = {'A', 'B', 'C', 'D', 'E'};
            for (int i=0; i<arr.length; i++) {
                if (arr[i]=='D')
                    return i;
            }
            return arr.length;
        }
    }

In the main() function, the following code segment can be used:

AClass anObj = new AClass();

int ret = anObj.simpleSearch();

System.out.println(ret);

The output is 3. Remember that the last index is array length minus 1. So if the length of the array is returned, it means the character looked for was not seen.

Conclusion

Once the length of the array is defined, it remains fixed until the end of the program. The array length is defined in the declaration of the array, with or without practical initialization. If the array length is not defined at declaration, then it still has to be defined, with an assignment, using the new operator. The array object also has the property, length, to return the length of the array. In Java, the property is called a field.

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.