Ok so I have this code:
public class Test {
public static void main(String[] args) {
String[] people = {"Bob", "Billy", "Jim"};
int sum = 0;
for(int i = 0; i < people.length; i++) {
sum += people[i].length();
}
}
}
My question is why people[i].length()
is .length()
and not .length
. I thought to get the length of an array you use .length
and not .length()
. Do you use .length()
because you are trying to get the length of a string and not an array? P.S. I am a beginner, so this may seem very obvious to you, but it isn't to me.
They're two completely different things.
.length
is a property on arrays. That isn't a method call.
.length()
is a method call on String
.
You're seeing both because first, you're iterating over the length of the array. The contents of the array are String
, and you want to add up all of their lengths, so you then call the length on each individual String
in the array.
.length
is an array property. .length()
is a method for the class String
(look here).
When you are looping, you are looping for the length of the array using people.length
.
But when you are using people[i].length()
, you are accessing the string at that position of the array, and getting the length of the string, therefore using the .length()
method in the String
class.
However, just to confuse you more, a String
at its core is just an array of char
s (like this: char[]
). One could make the argument that .length
should work as well, considering it is an array of characters, however, it is a class and that is the reason .length
will not work. Showing empty parameters shows it's a method, and showing no parameters shows that it's a property (like a static
variable in a class).
.length
is for Arrays, and .length()
for Strings
Array's length is a field, while the String's length is in a function - .length()
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