Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to display the sum of any no. of numbers.

Java Code Example — Polymorphism Programs

ADVERTISEMENT

Java Program to display the sum of any no. of numbers.

Objective

Write a Java program to calculate the sum of an arbitrary number of integers using Varargs.

Algorithm / Approach

  1. Create a class Addition.
  2. Define a method add(int ...a) using the varargs syntax (three dots).
  3. Inside the method, treat a as an array. Use an enhanced for-loop (for(int x : a)) to iterate through it.
  4. Add each number to a sum variable and print it.
  5. In main, call add() multiple times, passing 2 arguments, then 3 arguments, then 5 arguments.
Addition.java
class Addition {
 void add(int ...a) {
  int sum = 0;
  for(int x:a) {
   sum = sum + x;
  }
  System.out.println("Sum = "+sum);
 }
}
class Main {
 public static void main(String[] a)
 {
  Addition ob = new Addition();
  ob.add(2,3);
  ob.add(4,5,6);
  ob.add(3,4,5,6,7);
 }
}

Expected Output

Sum = 5
Sum = 15
Sum = 25

Explanation of the Program

  • Varargs (Variable-Length Arguments) is a powerful feature introduced in Java 5 that allows a method to accept zero or multiple arguments of the same type.
  • Before varargs, if you wanted a method to accept any number of arguments, you had to either heavily overload the method (add(a,b), add(a,b,c), add(a,b,c,d)) or force the user to create an array first.
  • Under the hood, Java simply packs the comma-separated arguments you pass into an array and hands that array to the method.

Complexity

Time Complexity O(n) - Where n is the number of arguments passed.
Space Complexity O(n) - For the implicit array created by Java.

Common Mistakes

  • Placing a vararg parameter at the beginning or middle of a method signature (e.g., void add(int ...a, String b)). The vararg must ALWAYS be the absolute last parameter in the list.
ADVERTISEMENT