Since Java 5 concepts were incorporated varargs (variable arguments) and loops for-each .
The first allows us to pass a variable number of arguments to a method in a transparent manner. The second gives us on way how loops are made.
Both features give us the same dynamism provided by other languages \u200b\u200blike Python or PHP.
Here's an example that blends these features
"Most Java programmers write code like this:
public class VarargsForEach {
public static void main (String [] args) {
for (int i = 0; i \u0026lt; ; args.lengt; i + +) {String argument = args
[i];
System.out.println (argument);
}}}
"Now using varargs and for-each loops, our code would be as follows: public class
VarargsForEach {public static void main (String. .. args) {
foreach (String argument: args) {System.out.println
( argument);}
print ("Hello," "As," "these," "...", 1,2,3, "bye");
} public static void print (Object.. . parameters) {
foreach (Object parameter: parameters) {System.out.println
(parameter);
}}}
The varargs give us more abstract and flexibility in the methods. On the other hand for-each loops give us simplicity and elegance in code.
0 comments:
Post a Comment