Java OCA OCP Practice Question 659

Question

Which of the following correctly defines a method named m that can be called by other programmers as follows:

m (str1) or 
m (str1, str2) or 
m (str1, str2, str3), 

where str1, str2, and str3 are references to Strings. 

Select 1 option

A. public void m (...String){ } 
B. public void m (String... strs){ } 
C. public void m (String [] strs){ } 
D. public void m (String a, String b, String c){ } 
E. Three separate methods need to be written. 


Correct Option is  : B

Note

To allow a method to take variable arguments of a type, you must use the ... syntax:

methodName ( <type>... variableName); 

Remember that there can be only one vararg argument in a method.

Further, the vararg argument must be the last argument.

So this is invalid:

m ( String... variableName, int age);  

but this is valid:

m (int age, String... variableName); 

Within the method, the vararg argument is treated like an array:

public void m (String... names){ 
   for  (String n  : names)  { 
       System .out.println ("Hello " + n);  
    } 
} 



PreviousNext

Related