Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How the subString() function of String class works

 
Harshit Rastogi
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
please see the following code.



I know that line 3 will still point to "Monday" and have a new String object with the offset and count set to 0,3.
The line 5 will create a new String "Mon" in string pool and point to it.
But not sure what about line 6 whether it will behave like line 3 or line 5.

If i am wrong for line 2 or 4 also please correct..
Thanks
 
Adeel Ansari
Ranch Hand
Posts: 2874
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check out the source of substring() method. Then you will find out that line 5 is instantiating the new String object redundantly.
 
Adeel Ansari
Ranch Hand
Posts: 2874
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This JR Thread might be helpful.
 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
substring always creates a new String object, except when the substring would actually be the String itself (i.e. the start is 0 and the end is equal to the String length).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic