Re: Strings...immutable?
On Mar 18, 10:51 pm, Patricia Shanahan <p...@acm.org> wrote:
John T wrote:
...
After doing a bit more studying, I've learned that it's the contents of
the string object that are subject to change, not the string itself,
hence the idea/rule that strings are immutable. Is this a correct
interpretation or do I need to go back to the books again?
No, the contents of a String object can never change.
Returning to a program I posted earlier in this thread:
1 public class Concatenate {
2 public static void main(String[] args) {
3 String s = "hello";
4 String x = s;
5 s += "good-bye";
6 System.out.println(x);
7 }
8 }
A reference variable such as s or x is either null, or a pointer to some
object.
At line 3, s is assigned a pointer to the object representing the String
literal "hello".
Pointers in Java? Ok.. I follow so far
At line 4, that pointer is copied to x. They now both point to the same
object.
Yup.. gotcha
Line 5 is equivalent to 's = s + "good-bye";'. The JVM creates a String
object representing the concatenation of the String object s references
and the one representing "good-bye". s is assigned a pointer to that
object.
I understand the concept of concatenation. Is 's' now a new String or
is
the old one reused?
The output at line 6 shows the value of the object x references, the
original, unmodified "hello".
But that doesn't make sense. If x and s are both pointing to the same
chunk of memory in which
is contained a string "hello", my reading has lead me to believe that
if you change s, x is
changed as well. so if you were to say s += "hello"; and then output
x, you would get the
same thing as if you output s.
Me going to try it now...
public class Concatenate {
public static void main(String[] args) {
String s = "hello";
System.out.println("Before assignment s is: " + s);
String x = s;
System.out.println("After assignment s is: " + s);
s += "good-bye";
System.out.print("After concat s is: " + s);
System.out.println(" and x is: " + x);
}
}
Output ----
Before assignment s is: hello
After assignment s is: hello
After concat s is: hellogood-bye and x is: hello
No String objects where modified in the course of this program.
So where the hell did I get the idea that x would change along with
s? Surely I didn't come up with it on my own?
Patricia