I wanted to make a program that outputs a string repeated a given number of times (separated by a space) using String.repeat
, but have been running into a java.lang.OutOfMemoryError
when the string is repeated too many times. How can I determine the maximum number of times a string can be repeated without causing an out of memory error?
I search online for the maximum length of a string and came up with 2147483647. In my code, I divide this maximum length by the length of the string to repeat. I wanted it to round off automatically, so I used the int
data type. I expected my program to be able to print the word, but instead of printing the result it still generates an out of memory error. Is the maximum string length correct? If not, what is the maximum string length?
import java.util.*;
public class Darshit {
public static void main(String[] Darshit1) {
Scanner Darshit = new Scanner(System.in);
System.out.println("WELCOME TO WORD RE-PRINTER!");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Enter the text");
String b = Darshit.nextLine();
int len = b.length()+1;
int e = 2147483647/len;
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("How many times you want to repeat the text");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Note ~>");
System.out.println("You can only print the word upto " + e + " times!");
int a = Darshit.nextInt();
String c = " ";
String d = b + c;
System.out.println(d.repeat(a));
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Thank you for using it");
System.out.println("Made by Darshit Sharma");
System.out.println("8th-C");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
}