Signup/Sign In
PUBLISHED ON: JANUARY 28, 2021

How to Multiply String in Java

In this tutorial, we will learn how to multiply Strings in Java. We will multiply String by using String.repeat() and StringBuffer.append() method of Java. Let's see some examples.

yesTo get the most out of this tutorial it is suggested that try all the code snippets and understand topics in a sequence.

Multiply string to repeat the sequence of characters.

String str = "StudyTonight";
String repeated = str.repeat(3);

The above code will support only Java 11 and above. Below that we need to use StringBuffer(). Why?

enlightenedStrings are immutable. It cannot be inherited, and once created, we can not alter the object.

Example

We are using the repeat() method of the String class to multiply strings and get a new string object.

public class StudyTonight 
{
	public static void main(String[] args)
	{
		String str = "Studytonight";		 
        System.out.println( str.repeat(3) );
	}
}


StudytonightStudytonightStudytonight

Example of Multiply String Using StringBuffer.append()

We use StringBuffer() to do operation on String and later we can use StringBuffer.toString() method to change into String.

public class StudyTonight {

	public static void main(String[] args) {

		//original string
		String str = "studytonight ";
		//number of times repetition 
		int n=5;
		//empty stringbuffer
		StringBuffer str_bfr = new StringBuffer();
		for(int i=0;i<n;i++)
		{
			//append string to stringbuffer n times
			str_bfr.append(str);
		}
		//converting stringbuffer back to string using toString() method
		str = str_bfr.toString();
		System.out.print(str);
	}
}


studytonight studytonight studytonight studytonight studytonight

Example of Multiply String Using String.replace()

It is the shortest variant of the same code but requires Java 1.5 and above versions. The awesomeness of this code is no import or libraries needed. Where n is the number of times you want to repeat the string and str is the string to repeat.

public class StudyTonight {

	public static void main(String[] args) {
		String str = "studytonight ";
		int n=5;
		String repeated = new String(new char[n]).replace("\0", str);
		System.out.print(repeated);
	}
}


studytonight studytonight studytonight studytonight studytonight

Conclusion

We can multiply string in java using appending a particular string in a loop using StringBuffer.append() and it will make sure that string is repeating n time. Another way is using String.replace() method where we pass null character ("\0") which is also known as an end of a string and the second parameter as a replacement of that character by the original string. String.repeat() is also able to perform the same reputation of String.



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.