aspose file tools*
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
Author

length Vs length()

Faraz Alig
Greenhorn

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:
myString.length()

But for an array, this statement is used:
myArray.length



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

Thanks,
Faraz
Janeice DelVecchio
Saloon Keeper

Joined: Sep 14, 2009
Posts: 1732
    
  12

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 ... ...


BEE MBA PMP SCJP-6
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: 3019
    
  10
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
Greenhorn

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

Regards,
Faraz
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.

-Hunter


"If the facts don't fit the theory, get new facts" --Albert Einstein
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: length Vs length()