-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 + ">>>>");
1
  • 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? Commented Oct 31, 2020 at 12:51

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.