File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
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.
I agree. Here's the link:
subject: array size
It's not a secret anymore!