Variable Arguments (Varargs)

6 0 0
                                        

class Varargs2nd{

          private String[] studentName;

          private int studentSize;

          public Varargs2nd(String... names){

                        studentName = names;

                        studentSize = names.length;

                       studentName = new String[studentSize];

                       for(int i=0;i<studentSize;i++){

                              studentName[i] = names[i];

                       }

         }

        public void displayName(){

                  for(String j: studentName){

                              System.out.println(j);

                  }

       }

}

public class VarargsDemo{

            public static void main(String[] args){

                   Varargs2nd v2 = new Varargs2nd("John doe", "bucky roberts", "serena williams", "Kristina Pimenova");

                  v2.displayName();

            }

}

/*Output:

       John doe

       bucky roberts

       serena williams

       Kristina Pimenova*/

================================================================================

variable arguments - an argument is the value that is pass to the parameter. Sorry if i misinformed last time. It did not sink in on my mind. So, the variable arguments are usually used if you don't know the number of arguments that you want to pass to the methods. A variable argument is an array since it receives multiple inputs but just located in the parameter section of the method.

================================================================================

/* Meaning of the word or symbol */

1.  for(String j: studentName){} - this is called an enhanced for loop. It function like the normal for loop except, that this is just a short cut but take note that in the normal for loop, you initialize a variable that is declared as integer to be used as an index while in enhanced for loop, you initialize a variable that is refer to the same type of the array which in here is a string.


Java codes i learned onlineWhere stories live. Discover now