javastringdynamicparameters

Java String... question regarding multiple inputs for a method


is it possible to create a class and have a String ... attribute that takes as many or as little strings as you put? example: please excuse my rough pseudocode, this is for java.

//this is the method:
public void getXXXX(String ...) {
//random code executes in a loop with as many as strings that are inputted
}

//this code calls it
getXXXX("Benjamin","Jordan","Steve")
getXXXX("Pengu","No")
getXXXX("hi")

Solution

  • Yes, what you entered will more or less work, you just need a parameter name after your type.

    class StringDecorator {
        public static String join(final String... strings) {
            final var builder = new StringBuilder();
            for (final var string : strings) {
                builder.append(string);
            }
        
            return builder.toString();
        }
    }
    

    Then invoke this somewhere

    StringDecorator.join("Hello, ", "World!"); // "Hello, World!"