Quick Reach
What is Java array length method?
Java array class comes up with the length() method by which you can get the size of an array. The length method returns int number which is the total elements in the given array.
See an example of array length
This is quite useful, for example, getting the total size that can be used in displaying array items with for loop.
How to use the length method of array
The syntax of using the length method is:
Arrname.length()
Where Arrname is the name of the array for what you want to get array size.
An example of getting the size of array
In this example, an array of three elements is created for demonstration purpose. After declaring and assigning the values, the length method is used for getting the size of that array.
The returned value after using the array length method is assigned to an int type variable. Finally, the size of the array is displayed:
1
2
3
4
5
6
7
8
9
10
11
|
public class demo_tst {
public static void main(String []args) {
String strState[] = {“New York”,“Texas”,“Florida”}; //declaring and assign values
//Getting the array length
int arr_length = strState.length;
System.out.println(“The array length is: “ + arr_length);
}
|
You can see, the array length is displayed as 3. The output of the above example will be:
The array length is: 3
Example of using length method of array with for loop
The example below uses the length method of the array to get total array elements and then it is used in for loop to display all items of arrays.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class array_ex {
public static void main(String []args) {
String strState[] = {“New York”,“Texas”,“Florida”}; //declaring and assign values
//Printing array
for (int i=0;i<strState.length;i++){
System.out.println(strState[i]);
}
}
}
|
See graphic of above example
The output will be:
New York
Texas
Florida
As you can see, the strState.length returned the length of given array that is used to loop through the strState array.
Also see: Java array | Java String array
Leave A Comment?