Easy Tutorial
❮ Java Print Parallelogram Data Replace ❯

Java Example - Using Varargs in Overloaded Methods

Java Examples

The following example demonstrates how to use variable arguments in overloaded methods:

Main.java File

public class Main {
    static void vaTest(int ... no) {
        System.out.print("vaTest(int ...): " 
        + "Number of arguments: " + no.length + " Contents: ");
        for(int n : no)
        System.out.print(n + " ");
        System.out.println();
    }
    static void vaTest(boolean ... bl) {
        System.out.print("vaTest(boolean ...) " +
        "Number of arguments: " + bl.length + " Contents: ");
        for(boolean b : bl)
        System.out.print(b + " ");
        System.out.println();
    }
    static void vaTest(String msg, int ... no) {
        System.out.print("vaTest(String, int ...): " +
        msg + "Number of arguments: " + no.length + " Contents: ");
        for(int n : no)
        System.out.print(n + " ");
        System.out.println();
    }
    public static void main(String args[]){
        vaTest(1, 2, 3);
        vaTest("Test: ", 10, 20);
        vaTest(true, false, false);
    }
}

The output of the above code is:

vaTest(int ...): Number of arguments: 3 Contents: 1 2 3 
vaTest(String, int ...): Test: Number of arguments: 2 Contents: 10 20 
vaTest(boolean ...) Number of arguments: 3 Contents: true false false

Java Examples

❮ Java Print Parallelogram Data Replace ❯