Why is String.length() a method, and int[].length a property (see below)?
int[] nums = {2,4,7,12,43};
String phrase = "Hello, world.";
System.out.length(nums.length);
System.out.length(phrase.length());
Why is String.length() a method, and int[].length a property (see below)?
int[] nums = {2,4,7,12,43};
String phrase = "Hello, world.";
System.out.length(nums.length);
System.out.length(phrase.length());
I don't think there has to be a good reason, and I think there could be many reasons.
But one is that by making String#length()
a property, it can be declared in an interface instead (in this case CharSequence
). Interfaces cannot declare public instance fields.
This is what the String::length()
function looks like:
public int length() {
return count;
}
So essentially count
could've been called length
and made public to be similar to arrays (it is final
after all).
It was probably just a design decision. There may have been some contributing factors that we can speculate about (one of which could've been the CharSequence
thing mentioned by Mark Peters).
Because String is not an array as such. The designers of Java designed arrays (which are objects) to have a public field named length
.
On the other hand, a String has a method which gives the length instead. In general it is a more conventional approach to make member fields private and use methods to access them, but in the case of arrays it is not.
They're different objects with different signatures as far as you are concerned. A String
is not a char[]
(although internally it might be implemented that way).
No particular reason, I think. In fact in C#, a very similar language, String.length
is a property http://msdn.microsoft.com/en-us/library/system.string.length.aspx. But take a look at what C# designer has to say about this design:
The Length property returns the number of Char objects in this instance, not the number of Unicode characters.
The reason is that a Unicode character might be represented by more than one Char. Use the
System.Globalization.StringInfo class to work with each Unicode character instead of each Char.
Why int[].length a property?
Arrays are special objects in java, they have a simple attribute named length which is final.
There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.
The public final field length, which contains the number of components of the array. length may be positive or zero.
The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].
A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.
All the members inherited from class Object; the only method of Object that is not inherited is its clone method.
Resource: JSL 10.7