Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use .length vs .length() [duplicate]

Tags:

java

arrays

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.

like image 336
RKWON Avatar asked Apr 30 '14 19:04

RKWON


3 Answers

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.

like image 136
Makoto Avatar answered Oct 24 '22 23:10

Makoto


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

like image 35
Michael Yaworski Avatar answered Oct 25 '22 00:10

Michael Yaworski


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

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

like image 37
Cdog101 Avatar answered Oct 24 '22 22:10

Cdog101