The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Object Basics and Simple Data Objects

More Accessor Methods

For the String Class

In addition to the length and charAt accessors you saw on the previous page, the String class provides two accessors that return the position within the string of a specific character or string: indexOf and lastIndexOf. The indexOf method searches forward from the beginning of the string, and lastIndexOf searches backward from the end of the string.

The indexOf and lastIndexOf methods are frequently used with substring, which returns a substring of the string. The following class illustrates the use of lastIndexOf and substring to isolate different parts of a filename.


Note:  The methods in the following Filename class don't do any error checking and assume that their argument contains a full directory path and a filename with an extension. If these methods were production code they would verify that their arguments were properly constructed.

// This class assumes that the string used to initialize
// fullPath has a directory path, filename, and extension.
// The methods won't work if it doesn't.
public class Filename {
    private String fullPath;
    private char pathSeparator, extensionSeparator;

    public Filename(String str, char sep, char ext) {
        fullPath = str;
        pathSeparator = sep;
        extensionSeparator = ext;
    }

    public String extension() {
        int dot = fullPath.lastIndexOf(extensionSeparator);
        return fullPath.substring(dot + 1);
    }

    public String filename() {
        int dot = fullPath.lastIndexOf(extensionSeparator);
        int sep = fullPath.lastIndexOf(pathSeparator);
        return fullPath.substring(sep + 1, dot);
    }

    public String path() {
        int sep = fullPath.lastIndexOf(pathSeparator);
        return fullPath.substring(0, sep);
    }
}
Here's a small program that constructs a Filename object and calls all of its methods:
public class FilenameDemo {
    public static void main(String[] args) {
        Filename myHomePage = new Filename("/home/mem/index.html",
                                           '/', '.');
        System.out.println("Extension = " + myHomePage.extension());
        System.out.println("Filename = " + myHomePage.filename());
        System.out.println("Path = " + myHomePage.path());
    }
}
And here's the output from the program:
Extension = html
Filename = index
Path = /home/mem
The extension method uses lastIndexOf to locate the last occurrence of the period (.) in the filename. Then substring uses the return value of lastIndexOf to extract the filename extension--that is, the substring from the period to the end of the string. This code assumes that the filename actually has a period in it; if the filename does not have a period , then lastIndexOf returns -1, and the substring method throws a StringIndexOutOfBoundsException.

Also, notice that extension uses dot + 1 as the argument to substring. If the period character is the last character of the string, then dot + 1 is equal to the length of the string which is one larger than the largest index into the string (because indices start at 0). However, substring accepts an index equal to but not greater than the length of the string and interprets it to mean "the end of the string."


Try this: Inspect the other methods in the Filename class and notice how the lastIndexOf and substring methods work together to isolate different parts of a filename.

While the methods in the example above use only one version of the lastIndexOf method, the String class actually supports four different versions of both the indexOf and lastIndexOf methods. The four versions work as follows:

indexOf(int character)
lastIndexOf(int character)
Return the index of the first (last) occurrence of the specified character.
indexOf(int character, int from)
lastIndexOf(int character, int from)
Return the index of the first (last) occurrence of the specified character, searching forward (backward) from the specified index.
indexOf(String string)
lastIndexOf(String string)
Return the index of the first (last) occurrence of the specified String.
indexOf(String string, int from)
lastIndexOf(String string, int from)
Return the index of the first (last) occurrence of the specified String, searching forward (backward) from the specified index.

For the StringBuffer Class

Like String, StringBuffer provides length and charAt accessor methods. In addition to these two accessors, StringBuffer also has a method called capacity. The capacity method differs from length in that it returns the amount of space currently allocated for the StringBuffer, rather than the amount of space used. For example, the capacity of the StringBuffer in the reverseIt method shown here never changes, while the length of the StringBuffer increases by one for each iteration of the loop:
public class ReverseString {
    public static String reverseIt(String source) {
        int i, len = source.length();
        StringBuffer dest = new StringBuffer(len);

        for (i = (len - 1); i >= 0; i--)
            dest.append(source.charAt(i));
        return dest.toString();
    }
}

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2001 Sun Microsystems, Inc. All rights reserved.