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?
.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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With