I like to do it a slightly different way which I think allows for more flexibility. It can eliminate the need for a lot of different overloading. The example method below eliminates the need of all the methods contained within your Test Class and allows for more flexibility, for example:
It can optionally accept NONE to an unlimited number of string
arguments:
new Test().method();
or
new Test().method("This is a String.");
or
new Test().method("This ", "is", " a", " string", " that", " will ", "be", " displayed.");
It can also accept a Single Dimensional (1D) String Array as a single
argument.
String[] stringArray = {This ", "is", " a", " string", " that", " will ", "be", " displayed."};
new Test().method(stringArray);
If you look at the Test Class below you can see that only one method is required:
public class Test {
public void method(String... args) {
if (args.length > 0) {
// Build the string from the supplied string arguments...
StringBuilder sb = new StringBuilder();
for (String strg : args) {
// A 'Ternary Operator' is used below in case an argument is null.
sb.append(strg == null ? "" : strg);
}
System.out.println(sb.toString()); // Display built string in console.
}
}
What can you do if the parameter for this method was: Object... args?
I sometimes use this technique for class Constructors as well, for example:
public class Test {
// Class Constructor
public Test (String... args) {
method(args);
}
public void method(String... args) {
if (args.length > 0) {
// Build the string from the supplied string arguments...
StringBuilder sb = new StringBuilder();
for (String strg : args) {
// A 'Ternary Operator' is used below in case an argument is null.
sb.append(strg == null ? "" : strg);
}
System.out.println(sb.toString()); // Display built string in console.
}
}
And to use it:
String[] stringArray = {"This ", "is", " a ", "string", " that", " will ", "be", " displayed."};
new Test(stringArray); // You will notice a warning but it works.
or
new Test(); // You will notice a warning but it works.
or
new Test("This is one Argument"); // You will notice a warning but it works.
or
new Test("This ", "is", " many ", "Arguments."); // You will notice a warning but it works.
or
Test test = new Test("This ", "is", " many ", "Arguments.");
or
Test test = new Test();
test.method("This is one Argument");
or
String[] args = {"This ", "is", " many ", "Arguments."};
Test test = new Test(args);
test.method(args);
The last example will display: This is many Arguments. twice in console. Can you see why?