substring method returns a new string that copies letters from an existing string, starting at the given index.
The first example returns a copy of the entire string. The second example returns all but the first two characters. As the last example shows,
substring returns the empty string if the argument is the length of the string.
To visualize how the
substring method works, it helps to draw a picture like Figure 9.4.1.
Like most string methods,
substring is overloaded. That is, there are other versions of
substring that have different parameters. If it’s invoked with two arguments, they are treated as a start and end index:
Notice that the character indicated by the end index is not included. Defining
substring this way simplifies some common operations. For example, to select a substring with length
len, starting at index
i, you could write
fruit.substring(i, i + len).