Java Reference
In-Depth Information
Pitfall It is a common error in Java to try to modify a string—for example by writing
input.toUpperCase();
This is incorrect (strings cannot be modified), but this unfortunately does not produce an error. The
statement simply has no effect, and the input string remains unchanged.
The toUpperCase method, as well as other string methods, does not modify the original string,
but instead returns a new string that is similar to the original one, with some changes applied (here,
with characters changed to uppercase). If we want our input variable to be changed, then we have
to assign this new object back into the variable (discarding the original one), like this:
input = input.toUpperCase();
The new object could also be assigned to another variable or processed in other ways.
After studying the interface of the trim method, we can see that we can remove the spaces
from an input string with the following line of code:
input = input.trim();
This code will request the String object stored in the input variable to create a new, simi-
lar string with the leading and trailing spaces removed. The new String is then stored in the
input variable because we have no further use for the old one. Thus, after this line of code,
input refers to a string without spaces at either end.
We can now insert this line into our source code so that it reads
String input = reader.getInput();
input = input.trim();
if(input.startsWith("bye")) {
finished = true;
}
else {
... Code omitted.
}
The first two lines can also be merged into a single line:
String input = reader.getInput().trim();
The effect of this line of code is identical to that of the first two lines above. The right-hand side
should be read as if it were parenthesized as follows:
(reader.getInput()) . trim()
Which version you prefer is mainly a matter of taste. The decision should be made mainly on
the basis of readability: use the version that you find easier to read and understand. Often, nov-
ice programmers will prefer the two-line version, whereas more experienced programmers get
used to the one-line style.
 
Search WWH ::




Custom Search