Length method

Taking the quiz for the String method and came to this question:

What will the following code print out?

String message = "how r u?";  System.out.println(message.length());

I chose 7 because Java recognizes 0 as the index number not 1 right? So why was it 8? I included the spaces and question mark as part my calculations.

The index does start at 0. But, the question isn’t asking for the index of the last character. The length method returns the total number of characters in the string. There are 8 characters in the given string (five letters, two spaces and one question mark). The last character '?' is located at index 7, but the length method doesn’t tell us the index of the last character. The length method answers the question how many characters there are in the string.

Thanks for replying. So essentially I have to count as I normally do and ignore the “index start at 0” computer rule when it comes to counting characters?

I don’t see why counting the total number of characters would require you to ignore the index.

Suppose we have a string like "Hello", then:

  • In a programming language such as JavaScript or Python, the index for strings/arrays starts at 0. So, the first character "H" will be at index 0 and the last character "o" will be at index 4. But the total number of characters (length) will be 5 regardless of the index.

  • In a programming language such as R or COBOL or Fortran the index for strings/arrays starts at 1. So, the first character "H" will be at index 1 and the last character "o" will be at index 5. But the total number of characters (length) will be 5 regardless of the index.

If we want to specify the index of a specific character(s)/element(s) of strings/arrays, then we must adhere to the indexing used by the particular programming language.

But for the total number of characters in a string, I don’t see how the index impacts the total number.

H    e    l    l    o
0    1    2    3    4
…
…
The characters are indexed 0 through 4 (index), but
the total number of characters (length) is still 5.

H    e    l    l    o
1    2    3    4    5
…
…
The characters are indexed 1 through 5 (index), but
the total number of characters (length) is still 5.

Length doesn’t refer to the index of the last character/element.
Length means the total number of characters/elements in a string/array.

1 Like

Thanks for the reply. I took Java years ago and remember the index starts at 0 but it’s been a while so I’m trying to make sense of it. haha