Var-Argument method:
Method which accepts any number of arguments is called var-argument method.
Syntax:
Access_Specifier Aceess_Modifier Return_Type methodName(DataType1... var1){
//Method body
}
Rule of Var-Argument method:
Output:
Number of arguments is 0
Number of arguments is 1 Hello
Number of arguments is 2 Hello World
Number of arguments is 3 Hello World Java
Example 2:
Output:
Number of arguments is 0 and addition result is: 0
Number of arguments is 1 and addition result is: 25
Number of arguments is 2 and addition result is: 40
Number of arguments is 3 and addition result is: 60
Method which accepts any number of arguments is called var-argument method.
Syntax:
Access_Specifier Aceess_Modifier Return_Type methodName(DataType1... var1){
//Method body
}
Rule of Var-Argument method:
- Only one argument should be variable argument
- Last argument should be var argument
Example 1:
package com.java.basics;
public class VarArgumentMethod {
public static void display(String... str){
System.out.print("Number of arguments is " + str.length + " ");
for (int i = 0; i < str.length; i++) {
System.out.print(str[i] + " ");
}
System.out.println(" ");
}
public static void main(String[] args) {
display();
display("Hello");
display("Hello", "World");
display("Hello", "World", "Java");
}
}
public class VarArgumentMethod {
public static void display(String... str){
System.out.print("Number of arguments is " + str.length + " ");
for (int i = 0; i < str.length; i++) {
System.out.print(str[i] + " ");
}
System.out.println(" ");
}
public static void main(String[] args) {
display();
display("Hello");
display("Hello", "World");
display("Hello", "World", "Java");
}
}
Output:
Number of arguments is 0
Number of arguments is 1 Hello
Number of arguments is 2 Hello World
Number of arguments is 3 Hello World Java
Example 2:
package com.java.basics;
public class VariableArgumentMethod {
public static int sum(int... va){
System.out.print("Number of arguments is " + va.length + " and addition result is: ");
int sum = 0;
for (int i = 0; i < va.length; i++) {
sum += va[i];
}
return sum;
}
public static void main(String[] args) {
System.out.println(sum());
System.out.println(sum(25));
System.out.println(sum(15, 25));
System.out.println(sum(10, 20, 30));
}
}
public class VariableArgumentMethod {
public static int sum(int... va){
System.out.print("Number of arguments is " + va.length + " and addition result is: ");
int sum = 0;
for (int i = 0; i < va.length; i++) {
sum += va[i];
}
return sum;
}
public static void main(String[] args) {
System.out.println(sum());
System.out.println(sum(25));
System.out.println(sum(15, 25));
System.out.println(sum(10, 20, 30));
}
}
Output:
Number of arguments is 0 and addition result is: 0
Number of arguments is 1 and addition result is: 25
Number of arguments is 2 and addition result is: 40
Number of arguments is 3 and addition result is: 60
No comments:
Post a Comment