×

Templates in C++ vs Generics in Java

As the title suggests, there is no rivalry or there is no cut comparison between generics and templates in Java and C++, respectively. The main aim of this article is to introduce you all to Generics in java and templates in C++.

While we are building some large-scale projects in organizations, we have a requirement that they have to be compatible with any input or any real-time test case that a user of the end application, whether it is in the form of a website or an application which is Android or IOS be it has to be universal to take any input to perform necessary job or function which it is assigned to do and give us a result applicational success.

Generics in Java or Templates in C++ essentially mean the same they support universal functionality with differing in very few cases; these are explained straightforwardly in the below code covering two different principles for each.

The C++ programming language requires us to template the sources to be added in their header places. While the Generics in Java programming language, when applied in a particular type of class then it will essentially get to be applied to the classes and the methods within that class.

C++ code (Templates-1)

//This is the C++ program we have written to   
//to illustrate and demonstrate the Templates use case along with outputs
#include <iostream>
#include <string.h>
using namespace std;
  
template <class Bh>
class temp_class {
  
    Bh value;
  
public:
    temp_class(Bh item)
    {
        value = item;
    }
  
    Bh getValue()
    {
        return value;
    }
};
  
int main()
{
    class temp_class<string>* String = 
      new temp_class<string>("Game between generics vs templates here ");
  
    cout << "Output Values: " << String->getValue() 
         << "\n";
  
    class temp_class<int>* integer = new temp_class<int>(19);
    cout << "Output Values: " << integer->getValue();
}

Output

Output Values: Game between generics vs templates here 
Output Values: 19

Java code (Generics-1)

//This is the java program we have written to   
//to illustrate and demonstrate the Templates use case along with outputs
public class GenericMethodTest {
   //here we are passing generic method printArray
   public static < E > void printArray( E[] inputArray ) {
      //here we are passing display array elements
      for(E element : inputArray) {
         System.out.printf("%s ", element);
      }
      System.out.println();
   }
   public static void main(String args[]) {
      // here we are creating arrays of Integer, Double and Character
      Integer[] int_Array = { 211, 32, 73, 84, 765 };
      Double[] double_Array = { 11.21, 52.2, 73.3, 744.24 };
      Character[] char_Array = { 'D', 'U', 'N', 'I', 'A' };
      System.out.println("Here the Array integerArray contains:");
      printArray(int_Array); //here we are passing an integer array
      System.out.println("\nHere the Array doubleArray contains:");
      printArray(double_Array); //here we are passing a Double array
      System.out.println("\nHere the Array characterArray contains:");
      printArray(char_Array); //here we are passing a Character array
   }
}

Output

Here the Array integerArray contains:
2113273 84 765 


Here the Array doubleArray contains:
11.2152.2 73.3 744.24 


Here the Array characterArray contains:
D U N I A 

C++ code (Templates-2)

//This is the C++ program we have written to   
//to illustrate and demonstrate the Templates use case along with outputs
#include <iostream>
#include <string>
using namespace std;
template <typename Bh>
inline Bh const& Max (Bh const& a, Bh const& b) {
   return a < b ? b:a;
}
int main () {
   int hi = 239;
   int bye = 120;
   cout << "Max(hi, bye): " << Max(hi, bye) << endl;
   double f1 = 113.50;
   double f2 = 120.722;
   cout << "Max(f1, f2): " << Max(f1, f2) << endl;
   string s1pro = "Hello";
   string s2pro = "Duniya";
   cout << "Max(s1pro, s2pro): " << Max(s1pro, s2pro) << endl;
   return 0;
}

Output

Max(hi, bye): 239
Max(f1, f2): 120.722
Max(s1pro, s2pro): Hello

Java code (Generics-2)

class Main_here {
  public static void main(String[] args) {


    // initialize generic class
    // with Integer data
    generics_class<Integer> int_Obj = new generics_class<>(15);
    System.out.println("generic class returns: " + int_Obj.getData());
    System.out.println();
    // initialize generic class
    // with String data
    generics_class<String> stringObj = new generics_class<>("Java Programming language is awesome");
    System.out.println("generic class returns: " + stringObj.getData());
  }
}


// create a generics class
class generics_class<bTs> {


  // variable of T type
  private bTs data;


  public generics_class(bTs data) {
    this.data = data;
  }


  // method that return T type variable
  public bTs getData() {
    return this.data;
  }
}

Output

generic class returns: 15
generic class returns: Java Programming language is awesome

Related Topics

Floating Point Operations and Associativity in C, C++ and Java

In this tutorial, we are going to compare Floating-point operations and the concept of associativity. Before we apply the concept of associativity in the floating-point operations in all three programming...

3 minutes read.

C++ Installation

Let's install C++ setup to start programming in C++. C++ setup contains C++ compiler which is required in your system. There are lots of C++ compilers available, you must choose...

1 minute read.

Splitting a string in C++

Any programming language must have the ability to work with string data. For programming needs, we sometimes need to separate string data. Many computer languages provide a split() method that...

4 minutes read.

Virtual class in C++

Introduction to Virtual Base class Virtual base classes can be utilized in virtual inheritance as a mechanism for examining many "instances" of a certain class while searching through multiple inheritances in...

6 minutes read.

Is it fine to write void main() or main() in C/C++?

In C programming language: The default function return type in the C programming language is "int," which implies that main() will always return an integer value. In C, the void main()...

3 minutes read.

C++ Interfaces

The C++ programming language provides programmers with a variety of capabilities and functions. It also enables object-oriented programming, which is essential while working on a project. It will be simple...

7 minutes read.

C++ int into String

Data type conversion is a standard editing process. You may need to convert variable from one type of data to another in a variety of situations. There are two ways...

5 minutes read.

C++ Constructor

Constructor is a specific method in C ++ that is automatically called when an object is created. Typically, it is used to set the data members of a new object....

4 minutes read.

C++ Namespaces

An Overview In each scope, a name can only represent one entity. As a result, there cannot be two independent variables with the similar names in the same scope, as this may cause...

10 minutes read.

C++ Algorithms

There are plenty of programming paradigms that are closely associated with the implementations of code and simulate them into a proper functional one. This is done with the help of...

5 minutes read.

C++ Range-based For Loop

In C++ language, the range-based for loop was added, which is far superior than the ordinary For loop. The implementation of a range-based for loop doesn't really need much code. It's a...

4 minutes read.

C++ Program to find the largest number formed from an array

Given an array, write a program to find the largest number that will be formed from the elements of the array. Arrangement should be done in such a way that...

4 minutes read.

External merge sort in C++

External merge sort in C++ External sorting is a concept for a group of sorting algorithms capable of handling large data volumes. External sorting is needed if the information getting sorted...

9 minutes read.

Exception Handling in C++ vs Java

Nowadays, exception handling is a feature found in virtually all object-oriented languages. We can also find this type of feature in Java and C++. The try-catch and block is required...

3 minutes read.

C++ Program to find the element that occurs once

Write a program to find the element in the array that occurs once. Given that all the numbers in the array are present two times and the array is sorted,...

7 minutes read.

C++ Exception Handling

Exception is an unexpected problem that occurs at program run time. This problem might include condition such as division by zero, running out of memory space, array out of bonds, etc....

2 minutes read.

This keyword in C++

This keyword in C++ is a pointer which points to the object. It is passed as an argument to functions which helps in accessing the object. It is used for a...

3 minutes read.

Hashing in C++

Before understanding hashing, we need to know what the use of hashing is. Let us consider an example of a library which consists of many books.Having many books, searching for...

6 minutes read.

C++ Program to Print Fibonacci Triangle

Fibonacci Triangle Program in CPP Definition: Fibonacci Triangle as the name suggests is the same as the Fibonacci number series where the next element is the sum of the previous two elements....

3 minutes read.

std::min in C++

std::min in C++ std::min is specified in the program code, used to calculate the lowest amount that has been transferred. When there's more of someone who returns first of them. It's used...

2 minutes read.