8

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.

Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97
RKWON
  • 109
  • 1
  • 1
  • 3

3 Answers3

27

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.

Makoto
  • 104,088
  • 27
  • 192
  • 230
3

.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 chars (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).

Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97
2

.length is for Arrays, and .length() for Strings

Array's length is a field, while the String's length is in a function - .length()

Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97
Cdog101
  • 100
  • 1
  • 9