Pages

Sunday, May 17, 2020

Java Var args (Variable Arguments) With Examples

Java Varargs (Variable Arguments) With Examples

Java 5 In-Depth usage of Var-Args - Variable Argument.


Java Varargs (Variable Arguments) With Examples


Varargs is introduced in Java 5 version. In this tutorial, we will discuss the following concepts on it.

1) Earlier versions what they had alternative for Varargs and its drawbacks.
2) Introduction to Varargs
3) Rules 

4) Advantages 
5) Disadvantages
6) Examples


In-Depth Tutorial on Var- Args in Java


More Core Java Concepts

Before Var-args concept:

First, Let us understand how these are implemented before var args concepts in java.
We have facility to use the same using the two options.

1) Method Overloading
2) Object array






1) Method Over Loading before var args:

As I have said, Using method overloading concept, we can use the same functionality for different in arguments.

In the below example, we can observe that BeforeVarArgsMethodOverloading class has a method named sum with different in arguments. but it supports for two or three numbers sum.

In case, If we want to get sum of 4 or more numbers than these two methods will not support.


Method Over Loading Example:


package java.w3schools.varargs;

public class BeforeVarArgsMethodOverloading {
    public static void main(String[] args) {
        BeforeVarArgsMethodOverloading beforeVarArgs = new BeforeVarArgsMethodOverloading();
        beforeVarArgs.sum(1, 2);
        beforeVarArgs.sum(1, 2, 3);
    }

    public void sum(int a, int b) {
        System.out.println("Sum of two numbers : " + (a + b));
    }

    public void sum(int a, int b, int c) {
        System.out.println("Sum of three numbers : " + (a + b + c));
    }
}


Output:

Sum of two numbers : 3
Sum of three numbers : 6


2) Object array as method argument:


Next, We can achieve sum of n numbers using Object array as method argument concept.


Object Array Example:


package java.w3schools.varargs;

public class BeforeVarArgsObjectArray {
    public static void main(String[] args) {
        Object[] array = { 1, 2, 3, 4, 5 };
        BeforeVarArgsObjectArray beforeVarArgs = new BeforeVarArgsObjectArray();
        beforeVarArgs.sum(array);
    }

    public void sum(Object[] array) {
        int sum = 0;
        for (int i = 0; i < array.length; i++) {
            sum = sum + (int) array[i];
        }
        System.out.println("Sum of " + array.length + " numbers : " + sum);
    }
}


Output:


Sum of 5 numbers : 15

In sum of n numbers, object array is good choice when compare to method overloading .
But, in object as argument it is required to type cast to the proper type as Object accepts any type. Since Object class is super class for all classes (root class).


Even if we use int array or String array then we have to create an instance of array with values and pass it to the method. Array size is fixed.


Introduction to Varargs:

Varargs concepts which allows to take zero or more parameters of same type which is alternative to the method overloading and object argument. There is no fixed size for varargs length.


Syntax:


ArguementType... varargsname


Usage:


Varargs are useful for any method that needs to deal with an indeterminate number of objects. One good example is String.format. The format string can accept any number of parameters, so you need a mechanism to pass in any number of objects. 

String.format("This is an integer: %d", myInt);
String.format("This is an integer: %d and a string: %s", myInt, myString);



Java Varargs (Variable Arguments) Rules:


1) We must declare the varargs type.
2) Its type can be primitive or wrapper or user defined type. Supports for all types.
3) Ellipsis symbol is indicated with three dot's as "..."
4) Ellipsis symbol is most important, should be present in between type and variable name as in syntax.
5) It is legal to have other variables along with varargs variable.
6) Varargs must be used only once in a method.
7) It should be last method argument in method.


Disadvantages:


1) we can not use multiple varargs in a method.
2) This will not work if vararg is at first arguement and not in last argument.


Example Program of Java Varargs (Variable Arguments) 

A) Varargs simple Example 1 (Legal):


public class VarArgsSimpleEx {
    public static void main(String[] args) {
        VarArgsSimpleEx beforeVarArgs = new VarArgsSimpleEx();
        beforeVarArgs.sum(1, 2);
        beforeVarArgs.sum(1, 2, 3);
        beforeVarArgs.sum(1, 2, 3, 4);
    }

    public void sum(int... values) {
        int sum = 0;
        for (int i : values) {
            sum = sum + i;
        }
        System.out.println("Sum of "+values.length+" numbers : " + sum);
    }

}


Output:


Sum of 2 numbers : 3
Sum of 3 numbers : 6
Sum of 4 numbers : 10


B) Varargs with other types (Legal):


public class VarArgsTotalMarksExample {
    public static void main(String[] args) {
        VarArgsTotalMarksExample beforeVarArgs = new VarArgsTotalMarksExample();

        beforeVarArgs.totalMarks("Jhon", 100, 90, 80, 70);
    }

    public void totalMarks(String studentName, int... marks) {
        int sum = 0;
        for (int i : marks) {
            sum = sum + i;
        }
        System.out.println(studentName+" total marks : " + sum);
    }
}


Output:   


Jhon total marks : 340


C) Multiple varargs exmple - Illegal:


    public void totalMarks(String studentName, int... marks, long... phoneNums) {
        // Some code here
    }

Compile time error saying: The variable argument type int of the method totalMarks must be the last parameter


D) Varargs at not at last position - illegal:


public void totalMarks(long... phoneNumbers, String studentName) {
    // Some code here
    }
   
Compile time error saying: The variable argument type int of the method phoneNumbers must be the last parameter

The above two cases got the same error message even though used multiple varargs. It it giving high priority to its placement.

Similar concept is available in C++ named Variadic template.


Hope you got everything about this topic.

Please leave your questions in comment section.

No comments:

Post a Comment

Please do not add any spam links in the comments section.