ptg7068951
70 HOUR 6:Using Strings to Communicate
Advanced String Handling
There are several other ways you can examine a string variable and change
its value. These advanced features are possible because strings are objects
in the Java language. Working with strings develops skills you’ll use on
other objects later.
Comparing Two Strings
One thing you are testing often in your programs is whether one string is
equal to another. You do this by using equals()in a statement with both
of the strings, as in this example:
String favorite = “piano”;
String guess = “ukulele”;
System.out.println(“Is Ada’s favorite instrument a “+ guess + “?”);
System.out.println(“Answer: “+ favorite.equals(guess));
This example uses two different string variables. One, favorite, stores the
name of Ada’s favorite instrument: a piano. The other, guess, stores a guess
as to what her favorite might be. The guess is that Ada prefers the ukulele.
The third line displays the text “Is Ada’s favorite instrument a”followed
by the value of the guessvariable, and then a question mark. The fourth
line displays the text “Answer:”and then contains something new:
favorite.equals(guess)
This part of the statement makes use of a method.Amethodis a way to
accomplish a task in a Java program. This method’s task is to determine if
one string has the same value as another. If the two string variables have
the same value, the text trueis displayed. If not, the text falseis dis-
played. The following is the output of this example:
Output▼
Is Ada’s favorite instrument a ukulele?
Answer: false
Determining the Length of a String
It also can be useful to determine the length of a string in characters. You
do this with the length()method. This method works in the same fashion
as the equals()method, except that only one string variable is involved.
Look at the following example: