It's not a secret anymore!*
The moose likes Java in General and the fly likes array size Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "array size" Watch "array size" New topic
Author

array size

Bill Walker
Greenhorn

Joined: Aug 22, 2002
Posts: 12
Is there a method that returns the number of elements in an array?
Jamie Robertson
Ranch Hand

Joined: Jul 09, 2001
Posts: 1879

array.length ?
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
String[] strings = new String[10];
System.out.println(strings.length); // prints 10
Note that length is a property and not a method.


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Shilpa Bhargava
Ranch Hand

Joined: Sep 15, 2002
Posts: 39
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

Joined: Feb 27, 2002
Posts: 8919

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.


Groovy
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
Also if you change the size of the array then you need to change everywhere you reference it by the hardcoded size.
 
jQuery in Action, 2nd edition
 
subject: array size