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 + ">>>>");