• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

array size

 
Bill Walker
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there a method that returns the number of elements in an array?
 
Jamie Robertson
Ranch Hand
Posts: 1879
MySQL Database Suse
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
array.length ?
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String[] strings = new String[10];
System.out.println(strings.length); // prints 10
Note that length is a property and not a method.
 
Shilpa Bhargava
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since Arrays are always fixed size, why would one want to use length on array when the size is always already known ??
For ArrayList and others it may be reqd ....
 
Pradeep bhatt
Ranch Hand
Posts: 8933
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider this:

public void printArray(int [] a)
{
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}

The method does not know the length of the array so it uses the field "length" to know the number of elements.
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also if you change the size of the array then you need to change everywhere you reference it by the hardcoded size.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic