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.