Working with instances of the immutable String class
The String
class, specifically the java.lang.String
class, represents character strings and is an immutable class that generates non-mutating objects. Hence, the methods provided by the String
class do not mutate the object.
For example, the following lines create a new String
, that is, a new instance of the java.lang.String
class named welcomeMessage
with an initial value of "Welcome to Virtual Creatures Land"
. Then, the code makes many calls to System.out.println
with welcomeMessage
followed by a different method as an argument. First, we call the toUpperCase
method to generate a new String
with all the characters converted to uppercase. Then, we call the toLowerCase
method to generate a new String
with all the characters converted to lowercase. Then, we call the replaceAll
method to generate a new String
in which the spaces were replaced by a hyphen (-
). Finally, we call the System.out.println
method again with welcomeMessage
as an argument...