• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Rob Spoor
  • Devaka Cooray
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Jj Roberts
  • Al Hobbs
  • Piet Souris

Strings confused!!!!please help me!

 
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
The more i study about strings the more i get confused.There were lot of discussions about strings earlier in this forum but still i am bewildered. I know that strings are immutable if that's the deal in the following case.
String s = "good"
s+= "morning" //isn't this wrong??? but it compiles well and prints goodmorning.
Haven't i changed the original contents of the string s.One more thing if it creates a new object by appending "morning" to "good" does that mean "good" is eligible for garbage collection now. How can i check for the immutability of the strings.
A deep explanation would be very helpfull.
Thank you very much.
 
Desperado
Posts: 3226
5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
sree: It appears that you are confusing the String reference <CODE>s</CODE> with a String object denoted by that reference, ("good"). And it appears that you almost answer your own question
When you do <CODE>s+</CODE> the old string is appended with the new one, the old one is discarded and now the same old object reference variable denotes a different string which is the concatenation result. As such, the original string is available for GC (if it's not in the String pool).
 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi sree,
What you're actually doing in your code is creating a new String object with the text "good morning" and assigning it to the variable s (don't confuse objects and the references that refer to them!) The original String that s referred to, "good", is still sitting there in the String pool, unchanged.
Because "good" was not created with the new operator, it was only created in the String literal pool, which doesn't have garbage collection. However, if you change the first line to
String s = new String ("good");
this creates a String object out with all the other objects, so it will be available for garbage collection as soon as it has no live references. In the case of this code, it will be available for garbage collection after its reference s has been assigned to the new String "good morning".
Hope that's clear!
 
sreelakshmi sarma
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Strings created using no "new" operator will not be available for GC no matter what is that right?? Only objects created using "new" will be eligible for "GC" ???
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
OK, this shouldn't come up on the exam, but I don't want this misinformation to continue to spread, so if you want to know about which kinds of strings are never collected, read on:
Sree- that's a myth I have been trying to stamp out lately. Forget about whether the new operator was used - that isn't what determines whether a string can be collected. There are many ways to create new strings without a visible "new" operator, and almost all of them create an ordinary String which can be collected. The only exceptions are:
  1. Strings which appear as literals in the code without any other operations being done to them, e.g.:
    <code><pre> String a = "literal";</pre></code>
  2. Strings which are the result of a constant-valued expression, e.g.
    <code><pre> String b = "not a " + "literal" + " but a constant";</pre></code>
    or
    <code><pre> String c = "Pi equals " + Math.PI;</pre></code>
    (because Math.PI is final, it's considered constant)
  3. Strings returned by the intern method, e.g.
    <code><pre> String d = anotherString.intern();</pre></code>

  4. Cases 1 and 3 should be easy to identiry; case 2 is a little harder - you have to look at each part of an expression to determine if it's a constant, i.e. if it's a variable, it needs to be final.
    All the above examples are put in the intern pool, and can never be collected. All other kinds of strings are "normal" and can be collected (if there are no more references). So in this example:
    <code><pre> String s = "good"
    s+= "morning";
    s = null;</pre></code>
    "good" is a literal and can never be collected, but "goodmorning" can be collected (<code>s += "morning"</code> is equivalent to <code>s = s + "morning"</code>, and since s isn't a constant, the expression <code>s + "morning"</code> isn't a constant expression).

    [This message has been edited by Jim Yingst (edited February 24, 2000).]
 
sreelakshmi sarma
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Jim,
Thank you very much.
 
sreelakshmi sarma
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
But what about the immutability of the strings. How can i check that.
String s = "good";
s+="morning";

A new string object(goodmorning)is created and assigned to the reference variable "s".Then what is this all fuss about immutablity.As long as it creates a new string object every time u change the value(or)string object in the old reference variable like in this case "s" why do we even have to worry about the immutable nature of strings.
I don't know whether i am making sense here or not.
Thanks.
 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yeah, you're making sense - it's a common misunderstanding. Basically, the String object is immutable, but the reference to it is not. The string "good" still exists unchanged, but now there's also a new string "goodmorning", and it's now the second string that s refers to. Once a string object is created, nothing can ever change it, except if it's garbage collected because there are no more references to it - and in the canse of "good", it's a literal, so that can't happen. But the string reference s can easily be reassigned to another string.
Try this:
<code><pre>public class Test {
public static void main(String[] args) {
String s = "immutable";
tryToChange(s);
System.out.println(s);
}
static void tryToChange(String s) {
s = "not " + s;
// Put any code you want to here.
// You won't be able to change the s back in main().
}
}</pre></code>
Try any code you want to in tryToChange() - the main() method will still print out "immutable", because the String class does not offer you any methods that allow you to change the string itself. For comparison, StringBuffer is not immutable - there are many ways to change a StringBuffer:
<code><pre>public class Test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("immutable");
tryToChange(sb);
System.out.println(sb);
}
static void tryToChange(StringBuffer sb) {
sb.delete(0, 2);
}
}</pre></code>
So what's immutability good for? Well, say you're working on a large project with a lot of people, and maybe some of them aren't such good programmers, and maybe it's a multithreaded environment, and you're writing a class or method that needs to use a particular String and maybe make it available to other parts of the program as well (parts not under your control), but you'd like to guarantee that your string won't change on you because of something someone else did in another part of the code. The immutability of strings handles this - you can let other parts of the program have a reference to your string, but they can't change the string itself. The only time it will change is if your code reassigns the reference to a different String. I.e. it can still happen, but it's under your control.
If that example seems improbable to you personally, consider that it's actually a decent description of the conditions Sun was working under when they designed the JDK. I'm not saying their programmers are bad, but they had to design the JDK to be used by others.
[This message has been edited by Jim Yingst (edited February 24, 2000).]
 
sreelakshmi sarma
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks again Jim. I really look forward for your messages. They are very concise.
 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks - though looking at some, like that one, I'm surprised to hear "concise". "Thorough", maybe, but not "concise".
 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think MY problem with this whole issue is that all the books and tutorials I've read only say, "Strings are immutable, harumph, harumph".
But they never even try to explain the details as you have done so well.
Thanks, and thanks to SREE for being persistant. This problem was really bugging me.
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
sree and Naruki
please read the JavaRanch Naming Policy, choose a username that complies with the rules and re-register.
Thank you very much for your cooperation

------------------
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Val, just take a look at the date of the original post...I doubt very much that sree is still hanging around
Shyam
 
Valentin Crettaz
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Woops, you're right...
Hopefully Naruki will read it though !
Thanks
------------------
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform
 
Ranch Hand
Posts: 241
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Naruki:

Thanks, and thanks to SREE for being persistant. This problem was really bugging me.


18 mths worth of persistence!
reply
    Bookmark Topic Watch Topic
  • New Topic