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.

Invoking Methods on Objects

In Section 4.8 we used a Graphics object to draw circles in a window, and I used the phrase "invoke a method on an object," to refer to the statements like

g.drawOval (0, 0, width, height);

In this case drawOval is the method being invoked on the object named g. At the time I didn't provide a definition of object, and I still can't provide a complete definition, but it is time to try.

In Java and other object-oriented languages, objects are collections of related data that come with a set of methods. These methods operate on the objects, performing computations and sometimes modifying the object's data.

So far we have only seen one object, g, so this definition might not mean much yet. Another example is Strings. Strings are objects (and ints and doubles are not). Based on the definition of object, you might ask "What is the data contained in a String object?" and "What are the methods we can invoke on String objects?"

The data contained in a String object are the letters of the string. There are quite a few methods the operate on Strings, but I will only use a few in this book. The rest are documented at the Java documentation site.

The first method we will look at is charAt, which allows you to extract letters from a String. In order to store the result, we need a variable type that can store individual letters (as opposed to strings). Individual letters are called characters, and the variable type that stores them is called char.

chars work just like the other types we have seen:

    char fred = 'c';
    if (fred == 'c') {
      System.out.println (fred);

Character values appear in single quotes ('c'). Unlike string values (which appear in double quotes), character values can contain only a single letter.

Here's how the charAt method is used:

    String fruit = "banana";
    char letter = fruit.charAt(1);
    System.out.println (letter);

The syntax fruit.charAt indicates that I am invoking the charAt method on the object named fruit. I am passing the argument 1 to this method, which indicates that I would like to know the first letter of the string. The result is a character, which is stored in a char named letter. When I print the value of letter, I get a surprise:


a is not the first letter of "banana". Unless you are a computer scientist. For perverse reasons, computer scientists always start counting from zero. The 0th letter ("zeroeth") of "banana" is b. The 1th letter ("oneth") is a and the 2th ("twoeth") letter is n.

If you want the the zereoth letter of a string, you have to pass zero as an argument:

    char letter = fruit.charAt(0);

Last Update: 2011-01-24