4

In Python, there is a * operator for strings, I'm not sure what it's called but it does this:

>>> "h" * 9
"hhhhhhhhh"

Is there an operator in Java like Python's *?

1
  • 8
    There is no such operator in Java. Commented May 29, 2013 at 11:30

7 Answers 7

9

Many libraries have such utility methods.

E.g. Guava:

String s = Strings.repeat("*",9);

or Apache Commons / Lang:

String s = StringUtils.repeat("*", 9);

Both of these classes also have methods to pad a String's beginning or end to a certain length with a specified character.

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

Comments

5

I think the easiest way to do this in java is with a loop:

String string = "";
for(int i=0; i<9; i++)
{
    string+="h";
}

3 Comments

Note that if you're going to do a LOT of concatenations, you should use a StringBuilder for performance. (Corollary: If it finishes in a blink of an eye, no optimization needed.)
String+=String in a loop is pure evil
See Effective Java by Josh Bloch, Item 51: Beware the performance of string concatenation
3

you can use something like this :

String str = "abc";
String repeated = StringUtils.repeat(str, 3);

repeated.equals("abcabcabc");

2 Comments

Might want to add a note about where StringUtils comes from.
you r right , you should Use apache libraries (common-lang) .
2

There is no such operator in Java, but you can use Arrays.fill() or Apache Commons StringUtils.repeat() to achieve that result:

Assuming

    char src = 'x';
    String out;

with Arrays.fill()

    char[] arr = new char[10] ;
    Arrays.fill(arr,src);        
    out = new String(arr);

with StringUtils.repeat()

    out = StringUtils.repeat(src, 10);

Comments

1
  • seems to be a repeat operator

Use apache libraries (common-lang) : Stringutils.repeat(str, nb)

Comments

1

String.repeat(count) has been available since JDK 11. String.repeat(count)

Comments

0

There is no operator like that, but you could assign the sting "h" to a variable and use a for loop to print the variable a desired amount of times.

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.