Java Reference
In-Depth Information
After printing the original phrase and its length, the
concat
method is executed
to create a new string object referenced by the variable
mutation1:
mutation1
"Change is inevitable, except from vending machines."
Then the
toUpperCase
method is executed on the
mutation1
object, and the
resulting string is stored in
mutation2:
mutation2
"CHANGE IS INEVITABLE, EXCEPT FROM VENDING MACHINES"
Notice that the
length
and
concat
methods are executed on
the
phrase
object, but the
toUpperCase
method is executed on
the
mutation1
object. Any method of the
String
class can be
executed on any
String
object, but for any given invocation, a
method is executed on a particular object. The results of execut-
ing
toUpperCase
on
mutation1
would be very different from the results of
executing
toUpperCase
on
phrase
. Remember, each object has its own state,
which often affects the results of method calls.
Finally, the
String
object variables
mutation3
and
mutation4
are initialized by
the calls to
mutation2.replace
and
mutation3.substring
, respectively:
KEY CONCEPT
Usually a method is executed on a
particular object, which affects the
results.
mutation3
"CHANGX IS INXVITABLX, XXCXPT FROM VXNDING MACHINXS"
mutation4
"NGX IS INXVITABLX, XXCXPT F"
SELF-REVIEW QUESTIONS
(see answers in Appendix N)
SR 3.6
Assume
s1
,
s2
, and
s3
are
String
variables initialized to
"Amanda"
,
"Bobby"
, and
"Chris"
respectively. Which
String
variable or variables
are changed by each of the following statements?
a.
System.out.println (s1);
b.
s1 = s3.toLowerCase();
c.
System.out.println (s2.replace('B', 'M'));
d.
s3 = s2.concat(s1);
SR 3.7
What output is produced by the following code fragment?
String s1 = "Foundations";
String s2;
System.out.println (s1.charAt(1));
s2 = s1.substring(0, 5);
System.out.println (s2);
Search WWH ::
Custom Search