Varargs In Java

Good day, readers. We will talk about varargs in java in today’s topic. Before writing a Java program, it is essential to understand these fundamental ideas. Before these, we also covered decision-making, loop control, and Java methods in case you missed them. Now, hurry up! Other Java-related topics, including Difference between C++ & Java, Operators in Java, Data Types in Java, and many others, have also been briefly discussed in the past. This information will be very helpful to your understanding. So let’s get to the point without further hesitation:

What is Varargs in Java?

Variable arguments are abbreviated as “varargs.” An argument of a method in Java can take any number of values. Varargs is the name of this argument, which can accept a variable number of values. With the introduction of Varargs in Java 5, it is now easier to refer to methods that accept any number of parameters of a single type.

Syntax of Varargs

accessModifier methodName(datatype… arg) {
     // method body
}

… (three dots) is inserted into a method’s formal parameter to define vararg.

Let’s first examine the example without the use of varargs:

// Example of without using varargs in Java by GeektoCode
public class GeektoCode {
     public int add(int a, int b){
          return a+b;
     }
     public int add(int a, int b, int c){
          return a+b+c;
     }
     public static void main( String[] args ) {
          GeektoCode obj = new GeektoCode();
          System.out.println(obj.add(5,10));
          System.out.println(obj.add(5,10,15));
     }
}

OUTPUT:-

15
30

As you can see, in order to make the add() method work with three arguments, you had to overload it. What happens if the user wants to add 10, 20, or 1000 numbers? Varargs can be used to handle this in a tidy manner. Here is an example of code:

// Example of using varargs in Java by GeektoCode
public class GeektoCode {
     public int add(int … args){
          System.out.println("Args length is " + args.length);
          int sum = 0;
          for(int x: args){
               sum += x;
          }
          return sum;
     }
     public static void main( String[] args ) {
        GeektoCode obj = new GeektoCode();
        int sum2 = obj.add(5, 10);
        System.out.println("2nd Addition = " + sum2);

        int sum3 = obj.add(5, 10, 15);
        System.out.println("3rd Addition = " + sum3);

        int sum4 = obj.add(5, 10, 15, 20);
        System.out.println("4th Addition = " + sum4);

        int sum5 = obj.add(5, 10, 15, 20, 25);
        System.out.println("5th Addition = " + sum5);
    }
}

OUTPUT:-

Args length is 2
2nd Addition = 15
Args length is 3
3rd Addition = 30
Args length is 4
4th Addition = 50
Args length is 5
5th Addition = 75

No matter how many arguments are passed, the add() method in this case returns the total of the int parameters.

NOTE: Varargs can be very helpful in some circumstances, as you can see. Instead, use method overloading if you are certain of the number of arguments being passed to a method. Use overloading, as in the first example, if you know for a fact that the add() method will only be used to calculate the sum of either 2 or 3 arguments.

Java Vararg’s importance

  • Until JDK 4, we cannot declare a method in Java with a variable number of arguments. If there were changes, new techniques were developed. As a result, the code’s length increased, making it challenging to read. Varargs was introduced to address these problems.
  • Before JDK 5, there were two ways to handle variable-length arguments: one was to use an overloaded method, and the other was to put the arguments in an array and then pass the array to a method.
  • To address all of these issues, JDK introduced vararags, which enabled the declaration of methods with a variable number of arguments. It is by far the best and most straightforward choice.
  • Varargs have the benefit of requiring fewer overloaded methods, which results in less code.
  • Vararg Methods may also be overloaded, but doing so could result in ambiguity.
  • Array arguments and overloading were the two methods available before JDK 5 for dealing with variable length arguments.
  • In a method, there can only be one variable argument.
  • The final argument must be a variable argument (Varargs).

Thus, the primary subject of this article is Java’s varargs. I sincerely hope you can use this. Wait for this to meet in the next post, where we will discuss a brand-new aspect of Java. Thanks a lot.

Leave a Reply

Your email address will not be published.

Sorry
Sorry
Sorry
Sorry
Sorry
Sorry
Sorry