The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


The second String method we'll look at is length, which returns the number of characters in the string. For example:

    int length = fruit.length();

length takes no arguments,as indicated by (), and returns an integer, in this case 6. Notice that it is legal to have a variable with the same name as a method (although it can be confusing for human readers).

To find the last letter of a string, you might be tempted to try something like

    int length = fruit.length();
    char last = fruit.charAt (length);       // WRONG!!

That won't work. The reason is that there is no 6th letter in "banana". Since we started counting at 0, the 6 letters are numbered from 0 to 5. To get the last character, you have to subtract 1 from length.

    int length = fruit.length();
    char last = fruit.charAt (length-1);

Last Update: 2011-01-24