Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

length Vs length()

 
Faraz Alig
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1809
12
Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The length of an array is a property.

String.length() is a method.

 
Jim Hoglund
Ranch Hand
Posts: 525
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
...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
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The String class must implement the method length() (among others) because it implements the CharSequence interface.
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks all of you for your valuable inputs!!!

Regards,
Faraz
 
Hunter McMillen
Ranch Hand
Posts: 492
Firefox Browser Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you have trouble remembering that, there are some really good ide's like eclipse that check for mistakes like that.

-Hunter
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic