|
Use a String Reference to Call a String Method
A reference to a String is required to call one of the String methods. In the following Java code
String str;
str = "Lion";
the expression
str
is a reference to a String object. This reference can be used to call any of the String methods, such as
str.substring(0, 2)
There Are Many Expressions that Yield a String Reference
The following expressions also yield a reference to a String object:
"Lion"
new String("Lion")
str.substring(0,2)
str.toUpperCase()
str.toLowerCase()
str.replace('i', 'a')
"Lion" and new String("Lion") both create a new String object and give a reference to that newly created object. str.substring(0,2) both creates a new String object (with the characters "Li") and yields a reference to that newly created object. Just as the reference str can be used to call the substring method
str.substring(0,2)
the references yielded by the expressions listed above can be used to call any of the String methods:
"Lion".substring(0,2)
"Lion".toUpperCase()
str.substring(0,2).toUpperCase()
str.toUpperCase().substring(1, 3)
The above expressions create the following Strings, respectively:
"Li"
"LION"
"LI"
"IO"
Similarly, since str.substring(0,2).toUpperCase() creates a String (the String "Li") and a reference to that newly created string, we can take that reference and call another String method such as
str.substring(0,2).toUpperCase().replace('i', 'a')
to create the String "La".
Exercises
- Write some Java statements to take the word "several" and pull the word "ver" from the middle of the word. There are several ways to do this. Have s3 refer to the string "ver" that you pull out of "several". Start with this code:
String s1 = "several";
String s3;
- Write some Java statements to take any word, of four or more characters, and transform that word so that the first three letters are set to upper case (e.g., "therefore" is transformed to "THErefore"). Have s3 refer to the final result. Note that the solution to this problem requires several steps. Start with the code shown below:
String s1 = "therefore";
String s3; // you can create additional reference variables, if desired
|