It's not a secret anymore!
The moose likes Beginning Java and the fly likes length Vs length() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "length Vs length()" Watch "length Vs length()" New topic

length Vs length()

Faraz Alig

Joined: Mar 14, 2010
Posts: 24
Hi Experts,

In Java, if one wants to know the length of a String, then below statement is used:

But for an array, this statement is used:

Why can't the same type of length works at both place.

Janeice DelVecchio
Saloon Keeper

Joined: Sep 14, 2009
Posts: 1789

The length of an array is a property.

String.length() is a method.

When you do things right, people won't be sure you've done anything at all.
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
...and myArray.length is an integer attribute of the array.
I agree that it's a bit confusing. The way I remember it is
to think of arrays as "a bit more primitive" than a String
object, for example.

Jim ... ...

Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

The String class must implement the method length() (among others) because it implements the CharSequence interface.

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3028
Also, all collections have a size(). So if you work with arrays and Strings and collections, you need to remember whether to use length or length() or size(). Three ways to refer to basically the same concept. Why this unnecessary confusion?

Ultimately, I think this is one of those things where early on, when Sun engineers where developing the Java language and platform, some things were done quickly, under tight deadlines, that we might today consider, ummm, errors of judgement, or inconsistencies, or at least non-intuitive choices. If they did it again today, knowing what they know now, many things would be different. But history didn't happen that way, and today we're stuck with decisions made over a decade ago.
Faraz Alig

Joined: Mar 14, 2010
Posts: 24
Thanks all of you for your valuable inputs!!!

Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 492

If you have trouble remembering that, there are some really good ide's like eclipse that check for mistakes like that.


"If the facts don't fit the theory, get new facts" --Albert Einstein
I agree. Here's the link:
subject: length Vs length()
It's not a secret anymore!