-2

I want to repeat string 's' and get a large string which has 'n' characters, and want to find how many 'a's in the large string. My code is below and it gives me "OutOfMemoryError: Java heap space" Error and couldn't find a solution for this problem

    String s = "abcab";
    long n = 1000000000000l;

    int strLength = s.length();
    double temp = n / strLength;
    long tempTwo = (long) temp + 1;

    long countOfAs = 0;

    // making large String
    StringBuilder sb = new StringBuilder(s);
    for (long i = 0; i < tempTwo; i++) {
        sb.append(s);
    }
    //take the sub string which's length is n
    String out = sb.substring(0, (int) n);

    //Find 'a's in the sub string
    char[] stringToCharArray = out.toCharArray();
    for (int i = 0; i < n; i++) {
        if (stringToCharArray[i] == 'a') {
            countOfAs += 1;
        }
    }
    System.out.println(countOfAs + ">>>>");
Rukshan
  • 127
  • 1
  • 12
  • 7
    You try to build a string with a length of 1.000.000.000.000 characters, which would result in 2.000.000.000.000 bytes. That's 2 TB of data. You don't think that might be a problem? – Progman Oct 31 '20 at 12:51

1 Answers1

1

Here you can see how to increase Heap size in Java:
Increase heap size in Java

There are easier ways to calculate the a's in your String, it is just:
countOfAs = n * 2;

Your code is wrong, because 2nd for loop must be "i < s.length() * n", because your String has more than one character.

If your String is really the size of 2 TB as commented by @Progman then you should think about an algorithm, which computes countOfAs in several intervals.

Elmar Brauch
  • 1,286
  • 6
  • 20