4

Suppose I have a string

msg = "hello"

Now I get substring from string msg like msg.substring(1,msg.length())

And storing that substring into msg.

So msg refers to new string. If the old string also remain in buffer of java and yes then how to access it?

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
uveng
  • 71
  • 8

2 Answers2

8

Note that String.substring() implementation and the actual implementation of String has changed with Java 7 (release 6, IIRC)

So depending on your Java version:

  1. if it's post Java 7u6, you can't do this. String.substring() will give you a completely new string
  2. if it's an older version of Java, you could access the private underlying char array of your new String, and this is in fact the complete char array of your old string

Item 2 is particularly nasty, and I suspect beyond what you really want to achieve.

See here for more details behind the substring() implementation and how it's changed.

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
3

When there are no longer any references to a memory block (a Java object, which is your String msg), that memory can be reclaimed (collected). Which means old, unused object is automaticaly removed by the garbage collector, so there is no any easy way to do it.. More info about garbage collection here.

UPDATE. As it is mentioned by Brian Agnew in comments, this answer is correct for Java versions 7u6 and higher.

TheMP
  • 8,257
  • 9
  • 44
  • 73