11.2. Calling a Varargs Method

Let's see how we can call / invoke the varargs method we created earlier in VarArgsMehtod class. Look at section // 4. Following are the varargs method call in the below code.

			package javatutorial;

			/**
			 * Example class learn about fixed arity and 
			 * variable arity / varargs method in Java
			 * 
			 * @author f5java.com
			 */
			public class VarArgsMehtod {
				
				/**
				 * Prints name,age and salary details 
				 */
				// 1. Fixed arity method
				public void fixedArityMethod (int age, float salary, String name){
					System.out.println("Inside fixedArity method");
					System.out.println("Name : " + name);
					System.out.println("Age : " + age);
					System.out.println("Salary : " + salary);
				}
				
				// 3. Variable arity method : Note the following things 
				
				// 3a. ... notation indicates this is a varargs parameter
				// 3b. Only one varargs parameter in formal parameter list
				// 3c. Varargs parameter should always be the last parameter
				// 3d. String... address is treated as String[] address
				
				public void varibleArityMethod(String name, String... address){ // String[] address
					System.out.println("Inside Variable arity method");
					System.out.println(name + " Lenght of varargs parameter is : " + address.length);		
				}
				
				public static void main(String[] args) {
					// Instantiate and call the method
					VarArgsMehtod varargs = new VarArgsMehtod();
					
					System.out.println("Calling fixed arity method");
					// 2. Fixed arity method: the number of formal parameter and actual parameter should match
					// i.e. correct parameters has to be passed in method call as per method declaration
					varargs.fixedArityMethod(18, 5000.00f, "John");
					
					// 4. Following are the varargs method call
					// Notice you can send any number of arguments in varargs parameter.
					// In this case it is treated as String[] address
					
					varargs.varibleArityMethod("firstCall", "100", "Main Street");
					varargs.varibleArityMethod("secondCall", "200","Apt No 100","John R Road");
					varargs.varibleArityMethod("thirdCall", "Commerical Street");
				
				}
			}