Created
January 24, 2021 17:13
-
-
Save BT-ICD/21b8ddf85346df452792ca77e182baf4 to your computer and use it in GitHub Desktop.
Example of Varaible Number of Arguments in function. Addition function with variable number of arguments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* To learn about variable number of arguments to the function | |
* The three dots ( ... ) are used in a function's declaration as a parameter. | |
* These dots allow zero to multiple arguments to be passed when the function is called. | |
* The three dots are also known as var args . | |
* Varargs is a short name for variable arguments. | |
* */ | |
public class VariableArgumentsDemo { | |
public static void main(String[] args) { | |
int result ; | |
result = addition(10,20,30); | |
System.out.println("Sum is:"+result); | |
result = addition(1,2,3,4,5); | |
System.out.println("Sum is:"+result); | |
} | |
//Variable values operated as an array | |
//The ... syntax tells the compiler that varags has be used | |
//Note: A method can have variable length parameters with other parameters too, but one should ensure that there exists only one varargs parameter that should be written last in the parameter list of the method declaration. | |
static int addition(int ... values){ | |
int sum=0; | |
for(int value:values){ | |
sum+=value; | |
} | |
return sum; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment