Results 1 to 5 of 5
- 05-17-2007, 06:14 AM #1
Member
- Join Date
- May 2007
- Location
- Mumbai, India
- Posts
- 5
- Rep Power
- 0
Strings are immutable yet they can be changed ?
Hi
Trying to get the hang of Java.
In the String doc, its mentioned :But in that case how come this works ?Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings.
ThanksPHP Code:String s = "abcde"; System.out.println(s); s = "12345"; System.out.println(s);
- 05-19-2007, 01:49 PM #2
Member
- Join Date
- May 2007
- Posts
- 4
- Rep Power
- 0
because you are not changing the String, you are changing what the 's' reference points to.
in other words, 's' is NOT a String, it is a REFERENCE TO a String. 's' lives on the stack, and the String object containing "abcde" lives in the heap (let's not get into the String pool right now). when you run the line
s= "12345", a new String is created in the heap. 's' is changed to point to it, but the String "abcde" is still hanging around, unchanged.
- 05-19-2007, 02:00 PM #3
Member
- Join Date
- May 2007
- Location
- Mumbai, India
- Posts
- 5
- Rep Power
- 0
So when s references to 12345, does the string obj containing abcde get deleted from the heap ?
- 05-19-2007, 02:41 PM #4
Member
- Join Date
- May 2007
- Posts
- 4
- Rep Power
- 0
no.
String literals are a special case. whenever you have a double quoted string, it gets created in the string pool. these are not eligible for normal garbage collection.
the details are a little more than you need to know right now, but basically:
Strings are never changed. new strings can be created, and references re-assigned to them.
- 05-19-2007, 03:08 PM #5
Member
- Join Date
- May 2007
- Location
- Mumbai, India
- Posts
- 5
- Rep Power
- 0
Similar Threads
-
characters + strings
By Gilgamesh in forum New To JavaReplies: 3Last Post: 03-02-2008, 09:10 PM -
Comparison of Strings
By Cero.Uno in forum New To JavaReplies: 3Last Post: 02-11-2008, 02:46 AM -
Help with drawing strings!
By JavaInLove in forum AWT / SwingReplies: 1Last Post: 02-05-2008, 03:39 AM -
Why the panel text changed?
By ottawalyli in forum AWT / SwingReplies: 1Last Post: 12-17-2007, 05:56 AM -
Why the panel text changed?
By ottawalyli in forum SWT / JFaceReplies: 0Last Post: 12-16-2007, 04:16 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks