Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to add two numbers using generics.

Java Code Example — Collection Programs

ADVERTISEMENT

Java Program to add two numbers using generics.

Objective

Write a Java program to add two numbers of any numeric type using Generics.

Algorithm / Approach

  1. Create a class Test<T extends Number>.
  2. Create a method add(T a, T b).
  3. Convert both generic numbers to doubles using doubleValue() and add them.
  4. In main, instantiate the class for Integer, Float, and Double types and call add().
Test.java
class Test<T extends Number> {
 void add(T a, T b) {
 double c=a.doubleValue()+b.doubleValue();
 System.out.println(c);
 }
 public static void main(String[] a)
 {
  Test<Integer> t1=new Test<Integer>();
  Test<Float> t2=new Test<Float>();
  Test<Double> t3=new Test<Double>();
  t1.add(4,5);
  t2.add(2.5f,3.5f);
  t3.add(4.5,7.9);
 }
}

Expected Output

9.0
6.0
12.4

Explanation of the Program

  • Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods.
  • The syntax &lt;T extends Number&gt; is a Bounded Type Parameter. It restricts the generic type T to only be a subclass of the java.lang.Number class.
  • Because we bounded it to Number, we can safely call the doubleValue() method on a and b, allowing us to perform universal math regardless of whether the user passed an Integer or a Float.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT