Advertisement
Advertisement


Array Length in Java


Question

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?

2018/01/20
1
101
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.

2018/04/23
86
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!

2018/04/23

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".

2012/01/06

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.

2012/01/06

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.

2012/01/06

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.

2018/11/05

Source: https://stackoverflow.com/questions/8755812
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]