Java Reference
In-Depth Information
Exercise 5.8 Implement this improvement in your version of the tech-support1 project. Test
it to confirm that it is tolerant of extra space around the word 'bye'.
Now we have solved the problem caused by spaces surrounding the input, but we have not yet
solved the problem with capital letters. However, further investigation of the String class's
documentation suggests a possible solution, because it describes a method named toLowerCase .
Exercise 5.9 Improve the code of the SupportSystem class in the tech-support1 project
so that case in the input is ignored. Use the String class's toLowerCase method to do this.
Remember that this method will not actually change the String it is called on, but result in
the creation of a new one being created with slightly different contents.
Checking string equality
An alternative solution would have been to check whether the input string is the string 'bye'
instead of whether it starts with the string 'bye.' An (incorrect!) attempt to write this code could
look as follows:
if(input == "bye") { // does not always work!
The problem here is that it is possible for several independent String objects to exist that all
represent the same text. Two String objects, for example, could both contain the characters
'bye'. The equality operator ( == ) checks whether each side of the operator refers to the same
object , not whether they have the same value! That is an important difference.
In our example, we are interested in the question of whether the input variable and the string
constant 'bye' represent the same value, not whether they refer to the same object. Thus, using
the == operator is wrong. It could return false, even if the value of the input variable is 'bye'. 2
The solution is to use the equals method, defined in the String class. This method correctly
tests whether the contents of two String objects are the same. The correct code reads:
if(input.equals("bye")) {
This can, of course, also be combined with the trim and toLowerCase methods.
Pitfall Comparing strings with the == operator can lead to unintended results. As a general rule,
strings should almost always be compared with equals , rather than with the == operator.
2 Unfortunately, Java's implementation of strings means that using = = will often misleadingly give the
'right' answer when comparing two different String objects with identical contents. However, you
should never use = = between String objects when you want to compare their contents.
Search WWH ::

Custom Search