Saturday, 1 June 2013

Varargs example in Java

Varargs (Variable argument) Introduces in Java 5 and the syntax includes three dots … (also called ellipses). The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments. Varargs can be used only in the final argument position.


Example how it work:-
public class TestVarargs {

 
 public static void main(String... args) {

  String firstName = "Arun", lastName = "Kumar", nickName = "Anu";
  new TestVarargs().testValues(firstName, lastName, nickName); // Pass your string parameter

 }

 private void testValues(String... values) { // values is array of string you can check by loop or index

  /** ------- Check By Index_--- **/

  String[] getValues = values;
  System.out.print(getValues[0] + "\t");
  System.out.print(getValues[1] + "\t");
  System.out.println(getValues[2]);

  System.out.println("--------------------");
  System.out.println("--------------------");

  /** ------ Check By Loop ----- **/

  for (String name : values) {
   System.out.print(name + "\t");
  }

 }

}

OutPut:-------
Arun Kumar Anu
--------------------
--------------------
Arun Kumar Anu

No comments:

Post a Comment