2

In Python I can do this: print("a" * 2);

Output = aa

Is there a way in Java to do the same without loops?

user3779568
  • 51
  • 1
  • 1
  • 3
  • Alas no. Unless you count finding a third party library method that does this by hiding the loop from the caller ;) – Chris K Jun 27 '14 at 14:42
  • If by loops, you mean a library method, I am sure that method would have a loop implemented in it. There is no other way to do it. So, either way you are using a loop to do it. – A M Jun 27 '14 at 14:45
  • 1
    You have to loop, however in Java 8 you could do the looping in a fancy way `IntStream.range(0, 2).forEach(i -> System.out.print("a"));` – Syam S Jun 27 '14 at 15:00

2 Answers2

3

Try this:

String buildString(char c, int n) {
    char[] arr = new char[n];
    Arrays.fill(arr, c);
    return new String(arr);
}

Arrays.fill() is a standard API method that assigns the given value to every element of the given array. I guess technically it'll be looping 'inside', in order to achieve this, but from the perspective of your program you've avoided looping.

Ian Knight
  • 2,356
  • 2
  • 18
  • 22
3

While Java does not have a built in method of doing this, you can very easily accomplish this with a few lines of code using a StringBuilder.

public static void main(String[] args) throws Exception {

    System.out.println(stringMultiply("a", 2));
}

public static String stringMultiply(String s, int n){
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < n; i++){
        sb.append(s);
    }
    return sb.toString();
}

The function stringMultiply above does essentially the same thing. It will loop n times (the number to multiply) and append the String s to the StringBuilder each loop. My assumption is that python uses the same logic for this, it is just a built in functionality, so your timing should not be too much different writing your own function.

Mike Elofson
  • 2,017
  • 1
  • 10
  • 16