CS151 lecture notes, Fall 1999 Week 7, Monday Reading: chapter 7 Invoking methods on objects --------------------------- Most of the time, you just invoke a method: printBinary (17); If it's a non-void method, you usually do something with the result: int x = gcd (20, 12); In a couple of cases we have seen, you "invoke the method on an object" g.drawOval System.out.println g is the name of the Graphics object System.out is the name of the output stream The method name is like a verb. The object name is like the object of the verb (hence the name). Where should I draw the oval? On g. Which output stream should I use? System.out Object types and primitive types -------------------------------- You can only invoke methods on objects. Primitive types like ints, doubles, booleans, and chars are not objects. Strings are objects, as indicated by the capital letter. You can invoke methods on Strings. String methods -------------- For example, length() String fruit = "banana"; int len = fruit.length (); Don't forget the empty (), which distinguish a method that takes no arguments from a variable name. Another example, charAt() char letter = fruit.charAt (1); System.out.println (letter); This prints the oneth character of "banana", which is 'a' Like many things, charAt starts counting from zero!!! I will refer to the characters in a String as the zeroeth, oneth, twoth, and threeth, to distinguish them from what appear to be the first, second and third letters. If we start counting at zero, where do we stop? What do we get from the following? int len = fruit.length (); char last = fruit.charAt (len); A run time error (StringIndexOutOfBoundsException) Have to use len-1 to get the last character. index ----- An index is a value or variable that is used to "indicate" one of the elements of a set. In this case the set is the letters in the String. All indixes are integers. An index is one of the "roles" a variable plays (along with loop variable, lower and upper bound, counter and accumulator). Traversing a String ------------------- Write a loop that reads the characters of a String one at a time and prints them. Section 7.7