This week's book giveaway is in the Android forum.
We're giving away four copies of Head First Android and have Dawn & David Griffiths on-line!
See this thread for details.
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 Head First Android this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "array size" Watch "array size" New topic

array size

Bill Walker

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: 8927

Consider this:

public void printArray(int [] a)
for(int i=0;i<a.length;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

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.
Don't get me started about those stupid light bulbs.
subject: array size
It's not a secret anymore!