Lecture 30
Introduction to Strings
We have already encountered the Java String class:
- Can define variables and parameters that reference strings. You can assign values
to string names, and you can write methods that return Strings as results.
Recall from the unit on GUI items:
    String colorChoiceString = (String)colorMenu.getSelectedItem();
- Can describe strings in programs by placing double quotes around a sequence of characters:
    msg.setText("Got me!");
- Can glue together strings; can glue together a string and a numeric value to make a new string:
    mouseCount.setText("You clicked " + count + " times.");
- Can determine if two strings look the same by using the ”equals” method.
Again, recall from the unit on GUI:
    if (colorChoiceString.equals("Red")) {
You’ve been told to always use “equals()” to check for equality, rather than “==”
Object or Primitive?
We’ve learned that many types in Java fall neatly into one of two categories:
- Object types (e.g., FilledRect, Text, Choice)
- Described by a class definition
- Created using constructor and ”new” command
- Manipulated through invocation of methods.
- Non-object (primitive) types (int, boolean, double)
- Members of each of these types are described by constants such as 3, true, 49.7
- Manipulated through operator symbols like +, &&, ∗
Java considers String to be an object type. But Strings share features with both object and non-object
types.
- Can be created using a constructor and ”new” command.
- Can be described by constants (”hello”)
- Can be manipulated using an operator symbol (+)
- Can be manipulated by invoking methods. In fact, there are over 50 methods
in the String class!
String Methods
There are many methods that we can use with strings. BUT REMEMBER: Strings are immutable!
This means that methods don't actually change the string, they make a copy of the string with
the new changes, and return that copy. We'll talk about this in more detail in the days to come.
So far, we've only looked at a couple of methods:
- indexOf(String substring)
- indexOf(String substring, int fromIndex)
- length()
We can see how these, and other methods work by looking at our
StringsDemo program.