0

I have one question.

When we do

String str = "abc";

"abc" will become string literal and will reside under string pool.

If we have string in for loop like below:

private static void doByString() {
        String str;
        for(long l = 0; l < Long.MAX_VALUE; l++){
            str = str + "" + l;
        }
    }

It will be making a lot of string literals, and we have to use it in for loop.

In this type of situation, can we do something to minimize the making of string literals?

Can we use string builder in this case like :

private static void boByStringBuilder() {
        StringBuilder builder = new StringBuilder();
        for(long l = 0; l < Long.MAX_VALUE; l++){
            builder.append(l + "");
        }
    }
PyThon
  • 1,007
  • 9
  • 22
sorabh solanki
  • 480
  • 1
  • 7
  • 18
  • 1
    Yes that is one of the purposeses of StringBuilder. – Ashwinee K Jha Sep 02 '16 at 12:21
  • Similar questions: [here](http://stackoverflow.com/questions/1532461/stringbuilder-vs-string-concatenation-in-tostring-in-java) and [here](http://stackoverflow.com/questions/11942368/why-use-stringbuilder-explicitly-if-the-compiler-converts-string-concatenation-t). – Mena Sep 02 '16 at 12:22
  • Long story short, yes use a `StringBuilder` whenever the concatenation has any logic that prevents the compiler from implicitly replacing the `String` concatenation with a `StringBuilder`, e.g. in your loop here. – Mena Sep 02 '16 at 12:23
  • 2
    The two loops are functionally different. The first one is equivalent to `String str = "" + (Long.MAX_VALUE - 1);` (there's no appending done here - you may as well just do the final execution only). – Andy Turner Sep 02 '16 at 12:25

2 Answers2

4

It will be making a lot of string literals, and we have to use it in for loop.

This won't create any String literals. It will create Strings.

In this type of situation, can we do something to minimize the making of string literals?

No need, as it doesn't create any.

Can we use string builder in this case like

Both code uses a StringBuilder. The first example uses StringBuilder implicitly.

Note:

builder.append(l + "");

is the same as

builder.append(new StringBuilder().append(l).append("").toString());

You can write

private static void boByStringBuilder() {
    StringBuilder builder = new StringBuilder();
    for(long l = 0; l < BIG_NUMBER; l++) {
        builder.append(l); // less Strings
    }
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

No need to append empty string every time inside for loop, change the append statement to

private static void boByStringBuilder() {
    StringBuilder builder = new StringBuilder();
    for(long l = 0; l < Long.MAX_VALUE; l++){
        builder.append(l);

    }
}
PyThon
  • 1,007
  • 9
  • 22