length or length() ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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.)

13th Oct 2016, 12:39 PM
Sarthak Mathur
Sarthak Mathur - avatar
5 Answers
+ 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.
13th Oct 2016, 2:18 PM
Schindlabua
Schindlabua - avatar
+ 2
"length()" is method. "length" is parameter. Arrays don't have method length().
13th Oct 2016, 2:16 PM
Andrew Darvell
Andrew Darvell - avatar
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.
18th Oct 2016, 4:32 PM
Prarabdh Garg
Prarabdh Garg - avatar
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
30th Oct 2016, 12:06 AM
Леонид Порожнета
Леонид Порожнета - avatar
0
I think that length is a property of any array. It is one of the constructs of Java.
29th Dec 2016, 3:06 PM
Siddharth Bose
Siddharth Bose - avatar