Suppose I have the following code:

StringBuilder sb = new StringBuilder("521,214"); String[] result = sb.toString().split(","); 

My question is: does toString().split(",") generate 2 strings or 3 strings? I know that the result String array will have 2 strings - but the toString() call will also generate a string as well - that isn't returned?

Basically, I'm trying to limit the number of strings created for performance purposes and want to know if the toString() call brings the total number of strings created to 3?

4

3 Answers

There will be five String object created in total by these two lines:

  • "521,214" object passed to StringBuilder's constructor. This object is in the interned pool of strings,
  • "," String object passed to split. This object is also in the interned pool of strings,
  • An equivalent "521,214" object produced by toString. Each call of toString produces a new String object. There is no optimization to see if in identical string object has been requested before.
  • Two String objects for "521" and "214" produced by the split method

It goes without saying that a String[] array object will be created to hold "521" and "214" objects returned from the split method.

1

does toString().split(",") generate 2 strings or 3 strings

neither 2 nor 3, split returns an array object, that the array has been made of strings is another story...

if your question is how many strings are in that array then the answer is: it depends of how many tockens (",") are found in the original string that you are splitting...

It will create a String array with 2 strings in it.

You can test this anytime by printing out the array:

StringBuilder sb = new StringBuilder("521,214"); String[] result = sb.toString().split(","); for(String s : result) System.out.println(s); 

The method .split() will remove the string that you are splitting by.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy