Array Length in Java


I declared an array as shown below:

int[] arr = new int[10];

Then I assigned following values to the array:

arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;

Then I declared and initialized an integer variable:

int arrayLength = arr.length;

This will be useful to find actual size but is there any method to find logical size of the array?

1/20/2018 3:22:11 AM

Accepted Answer

It contains the allocated size, 10. The unassigned indexes will contain the default value which is 0 for int.

4/23/2018 5:17:18 AM

To find length of an array A you should use the length property. It is as A.length, do not use A.length() its mainly used for size of string related objects.

enter image description here

The length property will always show the total allocated space to the array during initialization.

If you ever have any of these kind of problems the simple way is to run it. Happy Programming!


Arrays are static memory allocation, so if you initialize an array of integers:

int[] intArray = new int[15];

The length will be always 15, no matter how many indexes are filled.

And another thing, when you intialize an array of integers, all the indexes will be filled with "0".


In Java, your "actual" and "logical" size are the same. The run-time fills all array slots with default values upon allocation. So, your a contains 10.


In this case, arr.length will return 10, the size of array you allocated. Logical size doesn't really apply here, as this is a fixed length array.

When you initialize the array:

int[] arr = new int[10];

Java will create an array with 10 elements and initialize all of these to 0. See the Java language spec for details of initial values for this and other primitive types.


int[] arr = new int[10];

arr is an int type array which has size 10. It is an array of 10 elements. If we don't initialize an array by default array elements contains default value. In case of int array default value is 0.

length is a property which is applicable for an array.
here arr.length will give 10.