Java array length example shows how to find array length in Java. The example also shows how to access array elements using the array length
property.
How to get array length in Java?
Arrays in Java are objects that can be created dynamically and hold a set of elements of the same type. Java array does not have any method that returns the size of an array, but instead array length is available as a final instance property named length
.
In order to get the array length, we need to access its length
property.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.javacodeexamples.basic; public class ArrayLengthExample { public static void main(String[] args) { String[] strArray1 = new String[2]; /* * To get array length in Java, use * length property of an array object. */ System.out.println("String array length is: " + strArray1.length); /* * You can also initialize array while * declaring it. */ String[] strArray2 = {"one", "two", "three"}; System.out.println("String array length is: " + strArray2.length); } } |
Output
1 2 |
String array length is: 2 String array length is: 3 |
Array length can be 0 or any positive number equal to the number of elements in the array.
How to use array length to check if the array is empty?
You can use the array length
property to check if the array is empty. If the length of the array is 0, the array is empty, otherwise not.
Example
1 2 3 4 5 6 |
String[] strArray1 = new String[]{"One", "Two"}; if( strArray1.length == 0 ) System.out.println("Array is empty"); else System.out.println("Array is not empty"); |
Output
1 |
Array is not empty |
Instead of if-else, you can also use Java ternary operator to check if the array is empty using the array length property as given below.
1 2 |
boolean isEmpty = (strArray1.length == 0 ? true : false); System.out.println( "Is array empty? " + isEmpty ); |
Output
1 |
Is array empty? false |
How to iterate array using array length?
If you want to iterate through elements of an array, you can use the array length
property along with the for loop as given in the below example.
1 2 3 4 |
String[] strNames = new String[]{"Jay", "Ray", "Mike"}; for( int i = 0 ; i < strNames.length; i++ ) System.out.println( strNames[i] ); |
Output
1 2 3 |
Jay Ray Mike |
Remember that the index of the Java array starts from 0. That means that the first element of an array is located at index 0 and goes up to an array size – 1 index. That is why we started the for loop at 0 the index and went up to array.length – 1 index.
This example is a part of the Java Array tutorial with examples.
Please let me know your views in the comments section below.