Java array length example

How to get array length in Java?

Java arrays are objects which can be created dynamically and hold set of elements of the same type. Java array does not have any methods which returns the size of an array, but instead array length is available as 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

packagecom.javacodeexamples.basic;

publicclassArrayLengthExample{

publicstaticvoidmain(String[]args){

String[]strArray1=newString[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 array is empty?

You can use array length property to check if the array is empty. If length of array is 0, array is empty, otherwise not.

Example

1

2

3

4

5

6

String[]strArray1=newString[]{"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 array length property as given below.

1

2

booleanisEmpty=(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 array length property along with the for loop as given in below example.

1

2

3

4

String[]strNames=newString[]{"Jay","Ray","Mike"};

for(inti=0;i<strNames.length;i++)

System.out.println(strNames[i]);

Output

1

2

3

Jay

Ray

Mike

Remember that index of Java array starts from 0. That means that first element of an array starts at index 0 and goes up to array size – 1 index. That is why we started for loop at 0 index and went up to array.length – 1 index.

About the author

rahimv

rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.