• Post Reply Bookmark Topic Watch Topic
  • New Topic

How does substring () inside String works?  RSS feed

 
Tushar Goel
Ranch Hand
Posts: 934
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was reading interview questions randomly on different sites and came across this question. They have mentioned that till 1.7 substring
holds reference to the original string. So if you even choose small part of bigger string, it can't be GC. This problem is resolved in 1.7.

I have checked src code for both 1.6 and 1.8 and doesn't find any difference in the implementation. Any idea?
 
Tushar Goel
Ranch Hand
Posts: 934
4
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I figured it out. By looking the code closly i found in java-6 same instance of the array keeps but in 1.8 values are copied.
 
Campbell Ritchie
Marshal
Posts: 56223
171
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are right
Pre‑Java7 implementations kept a reference to the whole backing array. If that is much larger than the substring it can cause a memory leak. It was the only instance (I think) where it was worth using the String copy constructor.
String s = myText.substring(123, 456); // Risk of keeping whole backing array
String s = new String(myText.substring(123, 456)); // No risk of memory leak
As you said, since Java7 that trick has been unnecessary.
 
Tushar Goel
Ranch Hand
Posts: 934
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Campbell..
 
Campbell Ritchie
Marshal
Posts: 56223
171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!