Lecture 15-A Varargs
Lecture 15-A Varargs
(CS F213)
COMMAND LINE AND VARIABLE
LENGTH ARGUMENTS
Lecture 15-A
Prof. Anita Agrawal,
BITS, Pilani-K.K.Birla Goa Campus
2/17/2023 11:12:33 AM Anita Agrawal CS F213 Object Oriented Programming 2
Command-Line Arguments
• Command line arguments is a methodology in which user can
give inputs through the console.
• Syntax:
(…) A variable-length argument is specified by three periods
2/17/2023 11:12:33 AM Anita Agrawal CS F213 Object Oriented Programming 4
Example:
Other parameters
• The varargs method can have other parameters too in
addition to varargs.
• But there can exist only one varargs parameter.
• The varargs parameter should be written last in the
parameter list of method declaration.
Example:
• int sum (int x, float y, double … z)
- The first two arguments are matched with the first two
parameters and the remaining arguments belong to z
2/17/2023 11:12:34 AM Anita Agrawal CS F213 Object Oriented Programming 7
class VarargOverload {
public void A(int ... args){
int sum = 0;
for (int i: args) {
sum += i;
}
System.out.println("sum = " + sum);
}
public void A(String ... args){
System.out.println("args.length = "+ args.length);
}
}
Class B {
public static void main( String[] args ) {
VarargOverload x = new VarargOverload();
x.A(1, 2, 3);
x.A("hello", "world");
}
}