CS 051 Fall 2011

Lecture 30

Introduction to Strings

We have already encountered the Java String class:
  1. 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();

  2. Can describe strings in programs by placing double quotes around a sequence of characters:

        msg.setText("Got me!");

  3. Can glue together strings; can glue together a string and a numeric value to make a new string:

        mouseCount.setText("You clicked " + count + " times.");

  4. 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:

Java considers String to be an object type. But Strings share features with both object and non-object types.

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:

We can see how these, and other methods work by looking at our StringsDemo program.