Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between length and length()? [duplicate]

I've noticed that when doing the length of an array you write something like:

arrayone.length;

However, for such things as array lists or a string, you write a bracket on the end, such as the following for the length of the String:

stringone.length();

What is the key reason for this and how do you know when to put the brackets or now?

like image 823
mino Avatar asked Dec 30 '11 02:12

mino


2 Answers

.length;

directly accesses a field member.

.length();

invokes a method (i.e. an accessor) to access a field member.

in the case of String, this is to be expected since it's immutable.

like image 58
mre Avatar answered Oct 02 '22 22:10

mre


Arrays are handled differently than Strings or ArrayLists or anything else that can be counted in Java. An Array is pretty much a native type and it's length can never be changed after it is initialized, so there's no need for encapsulation. The length variable can be directly exposed with no side effects.

The reason why String uses a method instead of a variable is because it internally uses a char[] that it doesn't want to expose publicly (for immutability/encapsulation), so it wraps the length variable in a length() method. It's the same reason ArrayList has a size() method instead of a length variable.

The only time you'll use the variable instead of the method is with arrays. Everything else will be methods. That is, you'll use the brackets for everything except arrays.

like image 27
Robert Rouhani Avatar answered Oct 02 '22 23:10

Robert Rouhani