Lecture 20 (Tychonievich) - String Methods

Lecture Date: Friday, February 27

For the email hunt project you’ll want to manipuate Strings. The best way to find out how to manipluate some type of object in Java is to search for “java 8 api ClassName. The page you’ll find (from docs.oracle.com) will start with a summary of the class and its purpose, then have a list of all the methods you can use, each with a link to a more in-depth description.

Each longer description will start with the header you’d use to write the method yourself; for example, public int lastIndexOf(String str, int fromIndex)

  1. public means any part of java may call the method; we’ll use public for all methods for the next few weeks.
  2. static (if present) means “it’s just a method we can run” instead of “it’s a behavior that needs a particular object to run on”. Math’s sqrt method is static because you don’t need to do new Math() first; Scanner’s nextLine is not static because you do need to do new Scanner first. We’ll only write static methods for the next week or so
  3. The return type, which is the type of value that comes back when you run the method. lastIndexOf has an int return type, meaning you can write int i = s.lastIndexOf("x",3); Other examples: sqrt returns a double, nextLine returns a String, and println and main both return nothing (denoted by using the void return type.
  4. The name of the method. You pick this.
  5. (
  6. Zero or more parameters. Each parameter looks like a variable definition: type name.
  7. ) {
  8. Code. If the return type was not void, you must include a return statement in the code, which looks like return 3; or return "hi"; or the like.
  9. }

In lecture we played with some of String’s methods and wrote some of our own as well.

From lecture: