Java Varargs

If you have been told to buy fruits for 100 rupees then you will have to find out which fruits you can buy based on your budget. In this scenario we do not know which fruits you will be buying hence you don’t know how many fruits you’ll need in advance, so you can use params to handle any number of items.
The array is a defined list of values. For example if you have been told to buy apples, oranges & bananas from a supermarket then we can define an array called fruit {apple, orange, banana}. The array always has a defined value.
Definition:
In Java, the varargs feature allows methods to accept a variable number of arguments. The varargs keyword is used to specify that a method’s parameter can accept zero or more arguments of a specified type. This is useful when the exact number of arguments is not known in advance.

Varargs Keyword:
    Java: Type… parameterName
        ○ Type is the data type of the arguments.
        ○ parameterName is the name of the parameter that will accept the variable number of arguments.

Basic structure:

public static void MethodName(Type… parameterName) {
    // Method implementation goes here
}

Scenario 1: Adding Numbers with Variable Arguments

In this scenario, we want to add a variable number of integer values. We use varargs to handle an unknown number of arguments.

Java Code:

public class Main {
    public static void main(String[] args) {
        int sum1 = sum(20, 30, 75);
        int sum2 = sum(45, 50);
        int sum3 = sum(10);
        System.out.println(“Sum1: ” + sum1);
        System.out.println(“Sum2: ” + sum2);
        System.out.println(“Sum3: ” + sum3);
    }
    // Define a method using varargs
    public static int sum(int… numbers) {
        int sum = 0;
        for (int num : numbers) {
            sum += num;
        }
        return sum;
    }
}

Output:
Sum1: 125
Sum2: 95
Sum3: 10

Explanation:

public static void main(String[] args)

This is the main method where the sum method is called with different sets of integer values.

int sum1 = sum(20, 30, 75);

Calls the sum method with the parameters 20, 30, and 75, and stores the result in the integer variable sum1.

int sum2 = sum(45, 50);

Calls the sum method with the parameters 45 and 50, and stores the result in the integer variable sum2.

int sum3 = sum(10);

Calls the sum method with the parameter 10, and stores the result in the integer variable sum3.

System.out.println(“Sum1: ” + sum1);

Prints the value of sum1 to the console, which is the sum of 20, 30, and 75.

System.out.println(“Sum2: ” + sum2);

Prints the value of sum2 to the console, which is the sum of 45 and 50.

Prints the value of sum3 to the console, which is the sum of 10.

Prints the value of sum2 to the console, which is the sum of 45 and 50.

public static int sum(int… numbers)

This method uses varargs to accept a variable number of integer arguments.

int sum = 0;

Initializes a variable sum with a value of 0 to hold the total sum of the numbers.

for (int num : numbers)

A for-each loop iterates over each integer in the numbers array.

sum += num;

Adds the current number (num) to the sum variable.

return sum;

Returns the total sum to the caller.

Scenario 2: Adding Numbers with a Fixed Array of Arguments

In this scenario, we know the exact number of arguments in advance. We use an array to pass these arguments to the method.

Java Code:

public class Main {
    public static void main(String[] args) {
        int[] numbers = {20, 30, 75, 45, 50, 10};
        int sum1 = sum(numbers);
        System.out.println(“Sum1: ” + sum1);
    }
    // Define a method that takes an array of integers as a parameter
    public static int sum(int[] numbers) {
        int sum = 0;
        for (int num : numbers) {
            sum += num;
        }
        return sum;
    }
}

Output:
Sum1: 230

Explanation:

public static void main(String[] args)

This is the main method where the sum method is called with an array of integers.

int[] numbers = {20, 30, 75, 45, 50, 10};

Defines an integer array named numbers and initializes it with values.

int sum1 = sum(numbers);

Calls the sum method with the numbers array as the argument and stores the result in the integer variable sum1.

System.out.println(“Sum1: ” + sum1);

Prints the value of sum1 to the console, which is the sum of all elements in the numbers array.

public static int sum(int[] numbers)

This method takes an array of integers as a parameter.

int sum = 0;

Initializes a variable sum with a value of 0 to hold the total sum of the numbers.

for (int num : numbers)

A for-each loop iterates over each integer in the numbers array.

sum += num;

Adds the current number (num) to the sum variable.

return sum;

Returns the total sum to the caller.

C# params Keyword Java varargs Keyword
Purpose Allows a method to accept a variable number of arguments of a specified type. Allows a method to accept a variable number of arguments of a specified type.
Syntax public static void MethodName(params Type[] parameterName) { // Method implementation } public static void methodName(Type… parameterName) { // Method implementation }
Usage The params keyword specifies that the method can take a variable number of arguments of the given type. Internally, these arguments are treated as an array. varargs allows a method to receive a variable number of arguments, which are treated as an array. It must be the last parameter in the method’s parameter list.

Summary
● Varargs: Allows a method to accept a variable number of arguments.
      ○ Definition: Type… parameterName
      ○ Scenario 1: Demonstrates using varargs to handle a variable number of arguments.
      ○ Scenario 2: Demonstrates using a fixed array to pass arguments when the number is known in advance.

Tasks:
1. Sum of Variable Number of Integers: Create a method sumParams that takes a variable number of integer arguments (int… numbers) and returns the sum of its elements. Test the method by passing different numbers of integers and printing the result.
2. Concatenate Strings: Create a method concatenateParams that takes a variable number of string arguments (String… strings) and returns a single concatenated string. Test the method by passing different numbers of strings and printing the result.
3. Find Maximum Value: Create a method findMaxParams that takes a variable number of integer arguments (int… numbers) and returns the maximum value. Test the method by passing different numbers of integers and printing the result.
4. Average of Variable Number of Doubles: Create a method averageParams that takes a variable number of double arguments (double… numbers) and returns the average of its elements. Test the method by passing different numbers of doubles and printing the result.
5. Product of Variable Number of Integers: Create a method productParams that takes a variable number of integer arguments (int… numbers) and returns the product of its elements. Test the method by passing different numbers of integers and printing the result.
6. Print Variable Number of Elements: Create a method printParams that takes a variable number of arguments of any type (Object… elements) and prints each element. Test the method by passing different numbers and types of elements and printing the result.

Course Video

YouTube Reference :

Frequently Asked Questions

Still have a question?

Let's talk

The training covers the use of varargs in Java, including syntax, practical examples, and common use cases.

Yes, it includes examples like summing numbers, creating flexible methods, and handling variable arguments.

Yes, exercises include creating methods with varargs and working with real-world scenarios.

Yes, the training is designed for beginners with step-by-step instructions and practical examples.

A Java IDE like Eclipse, IntelliJ IDEA, or an online compiler will suffice.

Yes, it covers how to use varargs alongside other method parameters.

Yes, the training is self-paced and accessible online anytime.

Yes, it explains that varargs are treated as arrays internally and demonstrates this with examples.

It typically takes a few hours to complete, depending on your learning pace.

Yes, this Java Varargs training is completely free on Iqra Technology Academy’s website.