Sitemap
Aldyputu

Aldyputu

Java: Method Variable Argument

2 min readDec 11, 2023

When we face real problem to create an app, we always use method that will process any number of data, from less to huge chunk I mean.

Lets write method without variable argument:

public class Main {

//method here
static void sayCongrats(String name, int[] values) {
var total = 0;

for (var value : values){
total =+ value;
}

var finalValue = total / values.length;

if (finalValue >= 75) {
System.out.println("Congratulation " + name + ", you passed!");
} else {
System.out.println("Sorry " + name + ", you failed.");
}

}

public static void main(String[] args) {

//create array values with score list on it
int[] values = {80, 75, 90, 75, 90};
sayCongrats("Putu", values);

int[] values = {60, 75, 75, 75, 65};
sayCongrats("Putu", values);
}
}

/*
Output
Congratulation Putu, you passed!
Sorry Putu, you failed.
*/

Our method created to receive array on the parameter. After we construct the method, we need to define the array var first and put it on the parameter, and then the program start work on the parameter from string to the list of integer. Finally the output printed based on the total score.

Get Aldyputu’s stories in your inbox

Join Medium for free to get updates from this writer.

Now lets try to write method on using Variable Argument

public class Main {

//method here
static void sayCongrats(String name, int... values) {
var total = 0;

for (var value : values){
total =+ value; //still the same we need to for loop to iterate array of int
}

var finalValue = total / values.length;

if (finalValue >= 75) {
System.out.println("Congratulation " + name + ", you passed!");
} else {
System.out.println("Sorry " + name + ", you failed.");
}

}

public static void main(String[] args) {

//right now we can directly write our array on the parameter
// and get the same result
sayCongrats(name:"Putu", values:80, 75, 90, 75, 90);

sayCongrats(name:"Putu", values:60, 75, 75, 75, 65);
}
}

/*
Output
Congratulation Putu, you passed!
Sorry Putu, you failed.
*/

Variable argument can used by putting “…” triple dot after we define data type of our array parameter, and then we can put variable array or put array list directly to the method parameter. Voila!

--

--