I found this answer on Stack Overflow:
length is constant which is used to find out the array storing capacity not the number of elements in the array
Example:
int a[] = new int[5]
a.length
always returns 5 which is called the capacity of an array, so length always returns the CAPACITY. but"number of elements in the array is called size"
Example:
int a[] = new int[5] a[0] = 10
Will result in
a.size = 1
anda.length = 5
.
size()
works with collection,length
works with arrays in java
(Difference between size and length methods? , 2017-09-06)
As this answer received five upvotes I thought it is correct. But there is actually no size attribute for arrays in Java. I know there's a method for ArrayLists. However, how can a.size
be equal to one if normal arrays are used? Am I missing something?