In my last article, I discussed how before the introduction of VarArgs, programmers had to deal with the requirement of methods. Here, I am going to discuss the VarArgs Methods, that allow you to deal with the requirement of variable number of arguments in a method. A variable length argument is specified by three periods. For example
static void VarMethod(int...v)The best way to access all the arguments in VarArgs methods, is to use a for-each loop. However, there are two restrictions with associated with VarArgs Methods.
- If the method is supposed to take different arguments, then, VarArgs argument must be at the end of the argument list. For example
int VarArgMethod(boolean flag, String name, int...args)
- Second restrictions restricts the number of VarArgs argument in argument list to one only.
- change the type of VarArgs argument.
- add a normal variable to the argument list.
package ClassIllustration; class VarArgs { static void VarArgMethod(String...args) { System.out.print("Number of Arguments received this time " + args.length + " Contents "); for(String x:args) { System.out.print(" " + x); } System.out.println(); } public static void main(String args[]) { VarArgMethod("The", "Java","Journal"); VarArgMethod("Your", "Confusion", "Buster"); VarArgMethod("A", "place", "to", "clear", "all", "your", "doubts"); VarArgMethod(); } }To compile the program
javac -d . VarArgs.javaTo run the program
java ClassIllustration.VarArgsThe output for the program is
Number of Arguments received this time 3 Contents The Java Journal Number of Arguments received this time 3 Contents Your Confusion Buster Number of Arguments received this time 7 Contents A place to clear all your doubts Number of Arguments received this time 0 ContentsStay tuned.
No comments:
Post a Comment