Java Reference
In-Depth Information
I want to make a few comments about the StringDemo program. I count five
string literals in the program: “Rich”, “Raposa”, “ “, “Name = “, and “Hello, “.
Each of these literals is converted to a String object. So when name is assigned
to first + “ “ + last, that is the concatenation of three String objects. Similarly,
“Name = “ + name is the concatenation of two String objects.
I specifically added the last two println() statements of the StringDemo pro-
gram to demonstrate the importance of order of operations. When s + pi +7 is
calculated, the s + pi occurs first, which is string concatenation, not addition.
This new string is then concatenated to a 7 to create the string “Hello,
Rich3.141597”.
In the last println() statement, the order was changed, and pi + 7 is evalu-
ated first. The 7 is an integer literal, and therefore is treated as int. So, pi + 7 is
a double plus an int, and the 7 is promoted to a double and the addition is cal-
culated, resulting in the double 10.14159. This double is concatenated to s, cre-
ating the string “10.14159Hello, Rich”.
The output of the StringDemo program is shown in Figure 2.5.
A String object in Java is immutable, meaning that the string of characters
being represented by a String object cannot be changed. For example, the
StringDemo program declared a String called name and assigned it to the lit-
eral “Rich”. The “Rich” string cannot be altered. If, for example, you want
name to be “RICH”, you would have to assign name to a new String object
“RICH”. You cannot change the individual characters of name.
It may seem like a waste of resources to have to create a new String
object each time a String is used, but having immutable strings actually
allows the JVM to efficiently handle strings. However, there are times
when you may want to alter a string's characters without having to create
new String objects each time. The sidebar on the StringBuffer class
discusses how this can be done.
Figure 2.5
Output of the StringDemo program.