Created
April 28, 2021 17:52
-
-
Save BT-ICD/578921c05aeed9763019784cc8e8991d to your computer and use it in GitHub Desktop.
Example: To learn about variable number of arguments for a function
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
/** | |
* Example: To learn about variable number of arguments for a function | |
* Varargs is a short name for variable arguments. | |
* In Java, an argument of a method can accept arbitrary number of values. | |
* This argument that can accept variable number of values is called varargs. | |
* In order to define vararg, ... (three dots) is used in the formal parameter of a method. | |
* | |
* 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. | |
* */ | |
public class VariableNumberOfArgumentsDemo { | |
public static void main(String[] args) { | |
int ans; | |
ans = sum(10,20,30,40); | |
System.out.println(ans); | |
} | |
public static int sum(int ... nums){ | |
int ans=0; | |
for(int data:nums){ | |
ans+=data; | |
} | |
return ans; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment