In Java, the length of an array represents the quantity of elements the array can accommodate. Java does not offer a built-in function for retrieving the length of an array. The array length in Java can be determined by accessing the length attribute associated with the array, which is done by referencing the array name.
Array length Attribute
In Java, there is a characteristic called length which is used to specify the size of an array. Each array comes with a built-in length attribute that indicates the array's size, representing the total number of elements it can hold. To access the length property, you can use the dot (.) operator along with the array's name. This property is applicable to various array types such as int, double, String, and so on. For instance:
int[] arr=new int[5];
int arrayLength=arr.length
In the provided code excerpt, 'arr' represents an integer array capable of accommodating 5 elements. 'arrayLength' is a variable designated to retain the array's length. The array length is ascertained by referencing the array name (arr) followed by the dot operator and the 'length' attribute. This process effectively determines the array's size.
Please consider that the length of an array defines its maximum capacity, which indicates the total number of elements the array can hold, regardless of how many elements are actually stored within it. In other words, the length property provides the overall size of the array. In cases where an array is initialized with elements upon creation, both length and size properties refer to the same value.
When considering the logical size in terms of the array index, it is important to note that the index of the array begins at 0. Therefore, to determine the logical size, we can calculate it as int arrayLength = arr.length - 1. This adjustment ensures that the logical or array index will consistently be one less than the actual size of the array.
Let's determine the size of the array using an illustration.
Example
public class Main {
public static void main(String[] args) {
//defining an array of type int named num
//The square bracket contains the length of an array
int[] num = new int[10];
//length is an Array attribute that determines the array length
int arrayLength=num.length;
//prints array length
System.out.println("The length of the array is: "+ arrayLength);
}
}
Output:
The length of the array is: 10
Explanation
The provided Java script, a segment of the ArrayLengthExample1 class, illustrates the process of determining the length of an array. In the main method, the syntax int num = new int[10]; is utilized to both declare and initialize an integer array with a size of 10. The length of an array is specified within square brackets during declaration. Subsequently, the script calculates the length of the num array by accessing the length attribute inherent in all Java arrays. This value is then assigned to the variable arrayLength. To conclude, the script utilizes System.out.println to display the array's length, conveying the capacity of elements the array can accommodate.
Example
public class Main {
public static void main(String[] args) {
//Initialising an array of type String named country
String[] country = { "India", "Australia", "Japan", "USA", "UAE", "Canada", "Brazil"};
//length is an Array attribute that determines the array length
int arrayLength=country.length;
//prints array length
System.out.println("The size of the array is: " + arrayLength);
}
}
Output:
The size of the array is: 7
Explanation
The Java code snippet presents the class ArrayLengthExample2, which includes a main method. Within this method, a String array named country is created and initialized with various country names. The code then utilizes the length attribute in Java to determine the total number of entries in the country array. The calculated length is stored in a variable named arrayLength. Finally, the program displays both the size of the array and the number of elements it holds using System.out.println. This example demonstrates the usage of Java's length attribute to determine an array's length and to display this information for reference purposes.
Example
public class Main {
private static void LengthOfArray(String[] array) {
//checks array is empty or not
if (array == null) {
//if the array is empty, prints the following statement
System.out.println("The array is empty, can't be determined the length.");
}
else {
//The length attribute of the Array class determines the length of an array
int arrayLength = array.length;
//prints the array length
System.out.println("The length of the array is: "+arrayLength);
}
}
public static void main(String[] args) {
String[] fruits = { "Guava", "Banana", "Apple", "Papaya", "Melon", "Strawberry"};
String[] alphabets = { "m", "p", "k", "l", "t" };
String[] numbers = { "12", "25", "63", "84", "90", "11", "54"};
//passing a null value to the function
LengthOfArray(null);
//passing the fruits array to the function
LengthOfArray(fruits);
//passing the alphabet array to the function
LengthOfArray(alphabets);
//passing the numbers array to the function
LengthOfArray(numbers);
}
}
Output:
The array is empty, can't be determined the length.
The length of the array is: 6
The length of the array is: 5
The length of the array is: 7
Explanation
The Java code snippet presented introduces a class named Main, housing a method named LengthOfArray. This method is designed to ascertain and communicate the length of a specified array of strings. Initially, it checks if the provided array is null or empty by evaluating its value. If the array is empty, a notification indicating the inability to compute the length is printed. Otherwise, the method utilizes the length attribute from the Array class to determine the array's length and exhibits the result. The functionality of LengthOfArray is exemplified in the main method by supplying various arrays, including a null value, an array containing fruits, alphabets, and numerals. Upon execution, the program displays the length of each array.
Iterating through the Array
An alternative technique is to loop through the array and tally the encountered elements. This method offers increased versatility and authority in managing the counting operation.
Example
public class Main {
public static void main(String[] args) {
int[] arr = new int[5];
int count = 0;
for (int element : arr) {
count++;
}
int arrayLength = count;
System.out.println("The length of the array is: " + arrayLength);
}
}
Output:
The length of the array is: 5
Explanation
To determine the length of the array, we start by setting a variable named total to 0. Subsequently, we traverse each element of the array using a for-each loop. During each iteration, the loop doesn't modify the elements; rather, it simply traverses through each element in the array. With each iteration, the total variable is incremented. This process effectively tallies the total number of elements present in the array.
Subsequently in the loop, the variable arrayLength is assigned the value of count to indicate the length of the array. Finally, the program utilizes System.out.println to display the array's length and its maximum capacity of elements.
Conclusion
Understanding how to determine the length of arrays in Java is crucial for skilled programming and algorithm creation. By utilizing Java's array length property efficiently, programmers can improve code clarity, boost performance, and simplify array manipulation, all of which are vital for building dependable and effective Java software solutions.
Java Array Length Property MCQs
- Which attribute is used to find the length of an array in Java?
- length
- size
- length
- getLength
Explanation: In Java, arrays use the length attribute (not method) to determine the number of elements they can hold. For example: arr.length.
- What does the expression arr.length return in Java?
- Number of elements currently stored in the array
- Index of the last element in the array
- Maximum capacity of the array
- Size of the array object in bytes
When the code snippet is executed, it will output the total number of elements that the array can accommodate, irrespective of whether the elements have been initialized or not.
int[] arr = new int[4];
System.out.println(arr.length);
- Error
Explanation: The array is initialized with size 4, so arr.length will return 4.
- If you want to get the last index of an array arr, what should you use?
- length + 1
- length
- length - 1
- size
Explanation: Array indices in Java start from 0, so the last index is always length - 1.
- Which of the following is TRUE about the length attribute in Java arrays?
- It is a method and should be called with parentheses.
- It only works for integer arrays.
- It returns the number of initialized elements in the array.
- It is available for all types of arrays, including int, double, String, etc.
The length attribute is applicable to arrays of both primitive and reference types.