
Mehran Sahami Handout #45A
CS 106A December 5, 2007
Solution to Section #9
Parts of this handout by Eric Roberts and Patrick Young
1. Primitive vs. Objects
In the first example, the student is thinking a little too literally about the expressions
they’ve written them, seeing them as what they want them to mean as opposed to what
they in fact do mean. The problem lies in the comparison:
(name == "Q")
The correct English translation of this statement is: compare the address of the object
name to the address of the constant string "Q". In other words, name is a reference to a
String object. Since name was read in from the user, this comparison will always return
false, as it cannot be the same underlying object as the constant string "Q". If we
actually want to compare the values held in those String objects, we should write:
name.equals("Q")
For comparing values, the == operator should only be used with primitive types, such as
int, double, boolean, and char. Variables that represent objects (like String) are
always references (addresses to some location in memory).
In the second example the code actually works as intended. In the expression:
(ch == 'Q')
we are using the == operator to compare the primitive type char. Se we are comparing
primitives (and not object references), the == operator is comparing actual char values
rather than memory addresses. This works just as we would want it to.
Continued on next page