Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Advanced String Handling 71

String cinematographer = “Stuart Dryburgh”;
int nameLength = cinematographer.length();


This example sets nameLength, an integer variable, equal to 15. The cine-
matographer.length()method counts the number of characters in the
string variable called cinematographerand stores this count in the
nameLengthinteger variable.


Changing a String’s Case


Becausecomputers take everything literally, it’s easy to confuse them.
Although a human would recognize that the text Harvey Keiteland the text
HARVEY KEITELrefer to the same thing, most computers would disagree.
The equals()method discussed previously in this hour would state
authoritatively that Harvey Keitelis not equal to HARVEY KEITEL.


To get around some of these obstacles, Java has methods that display a
string variable as all uppercase letters or all lowercase letters,
toUpperCase()and toLowerCase(), respectively. The following example
shows the toUpperCase()method in action:


String baines = “Harvey Keitel”;
String change = baines.toUpperCase();


This code sets the string variable changeequal to the bainesstring vari-
able converted to all uppercase letters—”HARVEYKEITEL”. The
toLowerCase()method works in the same fashion but returns an all-
lowercase string value.


Note that the toUpperCase()method does not change the case of the
string variable it is called on. In the preceding example, the bainesvari-
able is still equal to “Harvey Keitel”.


Looking for a String


Another common task when handling strings is to see whether one string
can be found inside another. To look inside a string, use its indexOf()
method. Put the string you are looking for inside the parentheses. If the
string is not found, indexOf()produces the value –1. If the string is found,
indexOf()produces an integer that represents the position where the
string begins. Positions in a string are numbered upwards from 0, begin-
ning with the first character in the string. In the string “The Piano”, the
text “Piano” begins at position 4.

Free download pdf