I\'m writing a method that receives any number of arguments and returns them modified. I have tried with varargs but it doesn\'t work, here you can see a simplified version of t
This is a classic example of how many people dont know the way in which varargs works. Varargs is simply a holder for an array which is created when the methods with varargs parameter is invoked. To make my point clearer,we must have a look at the bytecode of varargs:-
Your code this
String hello = "hello";
String world = "world";
addPrefix(hello, world);
becomes to this
addPrefix(new String[]{hello, world});
Since you do not have reference to your newly created array,you are simply printing the values of your original String objects ,hello and world
You need to explicity return the array reference and iterate over it to view the changes
public static String[] addPrefix(String... elements) {
for (int i = 0; i < elements.length; i++) {
elements[i] = "prefix_" + elements[i];
}
for (int i = 0; i < elements.length; i++) {
System.out.println(elements[i]);
}
return elements;
}