Overview
Language, like C and C++, has functions witch can accept variant type parameters, for example :printf("Customer %s stays in %s area and his Customer ID is %d ", name, address, custId);
printf, function accepts multiple parameters of different type. The declaration of this function is
int printf(char *format, ...) // "..." means arbitrary number of parameters
Objective
Like printf function, write a function in java to accept variant type parameters. In Java you can add an ellipsis (3 dots ...) for the last parameter. The syntax for variant type parameter as follows
public String appendString(String str, String ... strings) {
for (int i = 0; i < strings.length; i++)
{
str += " " + strings[i];
}
return str;
}
for (int i = 0; i < strings.length; i++)
{
str += " " + strings[i];
}
return str;
}
In Java variant type is the sequence of parameter. Hence, strings is treated as array in the code.
Yet our objective is not met. We want parameters of variant type, that means function to accepts combination of string and integers etc. So, instead of String we can pass Object as the last parameter as follows
public String appendString(String str, Object ... strings) { ...
Similarly, C# has keyword "params" to add variable types of parameters.
public string appendString(string str, params object[] strings) { ...