The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes cannot change strings? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "cannot change strings?" Watch "cannot change strings?" New topic
Author

cannot change strings?

Barry Andrews
Ranch Hand

Joined: Sep 05, 2000
Posts: 523

In the Exam Cram book, Chapter 3 states that Strings cannot be changed once initialized. Huh?!!! I do not understand this...
If I run and compile this:
String s = "This string";
s = "That string";
System.out.println(s);
My machine spits out That string when run. Am I not changing the string?? Please help. Thanks!!!
Jane Griscti
Ranch Hand

Joined: Aug 30, 2000
Posts: 3141
Hi Barry,
String types are really object references. They hold a reference to the place in memory where the string is stored.
When you enter <code>s = "That String"</code> the compiler actually replaces it with <code>s = new String("That string")</code> and returns an object reference the new string.
So, while it looks as if you've changed the string what's actually happened is that a new string object was created.
Hope that helps.
PS There is one exception to the above. Java maintains a string pool. Every time you create a string without explicitly using new or concatenating two strings; the compiler puts them in a memory pool. It checks there first to see if the string you're trying to create already exists; if it does it will return an object reference to the string in the pool; otherwise it creates a new string.

------------------
Jane


Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
Barry Andrews
Ranch Hand

Joined: Sep 05, 2000
Posts: 523

Ok, I suppose I understand this now. It is kind of strange to think of it that way though. Thanks for the info!
 
IntelliJ Java IDE
 
subject: cannot change strings?
 
Threads others viewed
Return type of web service..
Doubt in Sarga's Test1
String x = "hi" ; garbage collected ?
String object and GC ?
Concatenate all of the strings in an array
IntelliJ Java IDE