CSC 108H

How to see if two strings are equal

Finding out whether two strings are equal is often a source of difficulty for programmers who are new to Java. You can compare integer variables i and j by doing something like

	if (i == j) ...     // WRONG!

But strings are objects, not simple or "primitive" variables, and you can't just use the == operator to compare them.

Instead, you must use the "equals" method of one of the strings.

For example, suppose that you've read a string from input, and you want to find out if it contains the value "QUIT". Here's what you would do, assuming the name of the string variable is "line":

	if (line.equals("QUIT")) ...  // right

Warning

Sometimes the == operator works with strings! That doesn't mean we're wrong; it just means that there are some subtleties about how strings are stored. We'll get to them later in the course.