Repeat a string: Difference between revisions

Content added Content deleted
(add →‎Joy)
Line 1,236: Line 1,236:


=={{header|Java}}==
=={{header|Java}}==
There are a few ways to achieve this in Java.<br />
Starting with Java 11 you can use the ''String.repeat'' method.
<syntaxhighlight lang="java">
"ha".repeat(5);
</syntaxhighlight>
Which, if you view its implementation, is just using the ''Arrays.fill'' method.
<syntaxhighlight lang="java">
String[] strings = new String[5];
Arrays.fill(strings, "ha");
StringBuilder repeated = new StringBuilder();
for (String string : strings)
repeated.append(string);
</syntaxhighlight>
And if you look at the 'Arrays.fill' implementation, it's just a for-loop, which is likely the most idiomatic approach.
<syntaxhighlight lang="java">
String string = "ha";
StringBuilder repeated = new StringBuilder();
int count = 5;
while (count-- > 0)
repeated.append(string);
</syntaxhighlight>
<br />
Or
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}


There's no method or operator to do this in Java, so you have to do it yourself.
Before Java 11 there was no method or operator to do this in Java, so you had to do it yourself.


<syntaxhighlight lang="java5">public static String repeat(String str, int times) {
<syntaxhighlight lang="java5">public static String repeat(String str, int times) {