Overloading Varargs Methods in Java

Java 8Object Oriented ProgrammingProgramming

A method with variable length arguments(Varargs) can have zero or multiple arguments. Also, Varargs methods can be overloaded if required.

A program that demonstrates this is given as follows:

Example

 Live Demo

public class Demo {
   public static void Varargs(int... args) {
      System.out.println("\nNumber of int arguments are: " + args.length);
      System.out.println("The int argument values are: ");
      for (int i : args)
      System.out.println(i);
   }
   public static void Varargs(char... args) {
      System.out.println("\nNumber of char arguments are: " + args.length);
      System.out.println("The char argument values are: ");
      for (char i : args)
      System.out.println(i);
   }
   public static void Varargs(double... args) {
      System.out.println("\nNumber of double arguments are: " + args.length);
      System.out.println("The double argument values are: ");
      for (double i : args)
      System.out.println(i);
   }
   public static void main(String args[]) {
      Varargs(4, 9, 1, 6, 3);
      Varargs('A', 'B', 'C');
      Varargs(5.9, 2.5);
   }
}

Output

Number of int arguments are: 5
The int argument values are:
4
9
1
6
3
Number of char arguments are: 3
The char argument values are:
A
B
C
Number of double arguments are: 2
The double argument values are:
5.9
2.5
raja
Published on 15-Feb-2019 10:30:37
Advertisements