0
length or length() ?
In String and array, when I used length in the code playground, it worked properly. But in Command Prompt, it shows an error and it takes length() only. Now my question is that why we use length and not length()? (length is a function which requires parenthesis.)
5 Respuestas
+ 3
That's one of the odd things in java. Arrays don't have a length method/function, but a property. That is to say:
String string = "abc";
string.length(); // 3
List<int> list = Arrays.asList(1,2,3);
list.length(); // 3
but!
int[] array = {1,2,3};
array.length; // 3
array.length(); // Throws an error!
It is what it is, I don't think there is a particular reason for why they did it like that.
+ 2
"length()" is method. "length" is parameter. Arrays don't have method length().
0
String is not actually a variable, but an abstract class in java.
The .length() is a function, or a subprogram of the class string, which helps you to work with Strings more easily.
Thus, the () in front of the function name is used to enter an argument if it is required. Since the .length() function doesn't require an argument, it is left blank.
0
If you ask why length is made as a field rather than method, I guess the reason is in most common usage of it: for(int x=0; x<myArr.length; x++) Calling a method on each iteration would be very inefficient
0
I think that length is a property of any array. It is one of the constructs of Java.