JAVA, interpolate n times the same variable with String.format

I would like to interpolate the same variables n times using String.format method.

For example with

String value = "hi";
String interpolated = String.format(" %s %s %s %s ", value);

I expect

// " hi hi hi hi "

You could do that (while harcoded in terms of occurrence):

String value = "hi";

String interpolated = String.format(" %s %s %s %s ", IntStream.range(0, 4)
                                                              .mapToObj(i -> value)

You could variabilize it in this way :

 public String repeat(String string, int nbRepeat){
    return String.format(" " + IntStream.range(0, nbRepeat)
                                         .mapToObj(i -> "%s")
                                         .collect(Collectors.joining(" ")),
                          IntStream.range(0, nbRepeat)
                                           i -> string)

And use it :

repeat("hi", 4);
repeat("ho", 6);

String interpolation (included), You could do that (while harcoded in terms of occurrence): String value = "hi"; String interpolated = String.format(" %s %s %s %s ", IntStream.range(0, 4) . Java String format() method is used for formatting the String. There are so many things you can do with this method, for example you can concatenate the strings using this method and at the same time, you can format the output of concatenated string. In this tutorial, we will see several examples of Java String format() method.

..Isn't there cleaner way?

Well it depends on how you want to use it; if you want to avoid streams, you can use any of the below:

package sample;
import java.util.Arrays;
import java.util.Formatter;

public class JoinString {
    public static void main(String[] args) {
        String[] v = {"hi","hi","hi","hi"};
        System.out.println(String.join(" ", v));
        Formatter formatter = new Formatter();
        System.out.println( formatter.format("%1$1s %1$1s %1$1s", "hi"));
        System.out.format("%1$1s %1$1s %1$1s %n", "hi"); 

String interpolation, In computer programming, string interpolation is the process of evaluating a string literal Expansion of the string usually occurs at run time. Find variable- reference (placeholder), replace it by its variable-value. This algorithm In Java versions 5 and above, the static method String.format can be used for interpolation:. I am making a java app and i have some trouble while importing data from sql server to java arraylists. The database has some inserts and when i run main in java i am calling a method that does the jdbc and is filling some arraylists with data.

You can use below snippet :

String s = "hi";
    int n = 9;
    String interpolated  = String.format("%0"+ n +"d", 0).replace("0", s );
    System.out.println(interpolated );

Back to Basics: String Interpolation in C#, Format you can use string interpolation to produce much more readable code The same code written using C# 6.0 string interpolation looks like this: methods just as easily as local variables declared inside of the current method. Format() code with compile time expressions that are parameterized. Java String repeat(int count) Important Points. If the count is 0, the empty string is returned. If the count is negative, IllegalArgumentException is thrown. If the count is 1, the reference to this string is returned.

You can use for loop. refer below code.

    Scanner sc = new Scanner(;
    System.out.println("Enter word : ");
    String str =;
    System.out.println("times : ");

    int n = sc.nextInt();
    for(int i =0 ; i < n; i++){
        System.out.print(String.format("%s ", str));

Syntax, Groovydoc follows the same conventions as Java's own Javadoc. Here are a few examples of valid identifiers (here, variable names): Any Groovy expression can be interpolated in all string literals, apart from single and triple- single-quoted def multilineSlashy = /one two three/ assert multilineSlashy. contains('\n'). The expression n of the placeholder ${n} is evaluated to number 3.5. The number 3.5 is then transformed into a string '3.5', and inserted into the interpolation result: 'The number is 3.5'. If the placeholder contains an object, following the conversion to string rule, the object is converted to a string too.

If you are using java 11 you can use repeat() method like:

String value = "hi ";

To get interpolated string you can also use MessageFormat class:

String interpolated = MessageFormat.format("{0}, {0}, {0}", "hi")

The Do's and Don'ts of Java Strings You Should Know, An understanding of Java Strings will help you be prepared for also extremely important when representing dates/times and currency. You could use one of String's replace functions, but String.format is actually meant for this purpose: Introduced in Java 1.5, StringBuilder has the same interface as its� These variables are given a higher precedence than server.xml variables so that server.xml variables can be overridden at request time. Expressions Use expressions in If and ElseIf tags (see If, ElseIf, and Else ), in log format strings (see Appendix C, Using the Custom Log File Format ), and SAF parameters (see String Interpolation ).

How to Format a String in Python: Interpolation, Concatenation, and , In other words, it's time to finally learn how to format a string in Python 3.2 Format a String Using Multiple Print Statements like Java and C, string formatting relies on understanding concepts like variable That said, I don't you' re here to learn string formatting in C, so how do we accomplish the same thing in Python? By using any loop, like for , while and do-while loop. For example - String s = “Hello”; You want to repeat this string 10 times, i.e n=10. Now using for loop, for(int i=1 ; i&lt;=n ; i++) { System.out.println(s); // This line will print this string

Why is %s better than + for concatenation?, The format string syntax is more readable, as it separates style from the data. Java optimizes this case some of the times by transforming the series of easier to edit, you can change the template on one line and list of variables on another) strings and/or you want to concatenate multiple strings with the same separator . The most common way of formatting a string in java is using String.format(). If there were a “java sprintf” then this would be it. If there were a “java sprintf” then this would be it.

Scala String Interpolation In Depth, And also we will discuss similar kind of concept supported by Java Language. In Scala, String Interpolation means that the replacement of defined variables These rules are same for all kinds of String Interpolation. Here we can observe that if we use s String Interpolator to format numbers, we don't get expected result � For instance, in languages like Java and C, string formatting relies on understanding concepts like variable arguments and format specifiers: printf("Hi, %s", Jeremy); # Prints "Hi, Jeremy" Of course, string formatting gets more complicated as we introduce different data types.

  • Try String.format(" %s %s %s %s ", value, value, value, value)
  • You can try using a for-loop as well.
  • @Daniele isn't there cleaner way?
  • i need interpolation to using that string, not for printing only
  • @tommasoballardini Updated with MessageFormat.format method