×

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

swap() function in C++

Swap() function: swap() function in C++: swap() function is a pre-define function in c++ present in STL( Standard template library ). It is used to swap two numbers. It takes two mandatory...

6 minutes read.

Divide by Zero Exception in C++

We use exception handling method to handle the divide by zero exception. Dividing a number with zero is generally mathematical error. We have to exception handling method to overcome this...

2 minutes read.

C++ Maximum Index Problem

Given an array A[] of positive integers. We will find the maximum of (j-i) such that i and j are the indexes of A[] and A[i] <= A[j], i<=j For...

5 minutes read.

C++ this pointer

'this' is a pointer that points to the object for which this function was called. The 'this' pointer holds the memory address of the current object. The 'this' pointer is implicitly passed to...

2 minutes read.

Program that produces different results in C and C++

Introduction: There are many such programs that compile run both in C and C++ but give different outcomes when compiled by the C and C++ compilers. There are a variety of such...

6 minutes read.

Diamond Pattern Using Do-While loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

5 minutes read.

C++ Type Casting

The type casting of variables in the C++ programming language will be covered in this section. The term "type casting" describes how software converts one data type to another. There...

9 minutes read.

While Loop Examples in C++

While Loop A while loop repeats all code in its body, also known as a while statement, as long as a specific condition is satisfied. The loop ends if or when...

4 minutes read.

Vector Size in C++

What are Vectors?  In the C++ programming language, vectors are run-time sequence containers representing arrays with variable sizes, which are contained within STL (Standard Template Library). They utilize contiguous storage spaces...

6 minutes read.

C++ Close file

C++ File Handling close() Function A file which is opened while reading or writing in file handling must be closed after performing an action on it. The close() function is used to close...

2 minutes read.

Template Specialization in C++

Template is a feature of C++. With the help of a template, we can write the code only once and use that code multiple times. For example, there is a...

4 minutes read.

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++ | C Plus Plus Data type

Data type in every language is very important. Data type means the different kinds of data that are supported by a particular programming language. A computer language’s data types specify the...

15 minutes read.

4-Dimensional Array in C/C++

A four-dimensional (4D) array is an array of three-dimensional (3D) arrays, or in other words we can say that a 4- dimensional array is an array of arrays of arrays...

3 minutes read.

How to Handle Divide by Zero Exception in C++

If you are a programmer or interested in coding then it is obvious that you face some illogical test cases. Suppose, you have written one program that calculates the factorial...

6 minutes read.

Virtual base class in C++

Consider in a C++ program, there are 4 classes named class A, class B, class C, and class D. If class B and class c inherit properties from class A....

3 minutes read.

rand() and srand() in C / C++

In this tutorial, we'll explore the syntax, usage, and examples of the C++ STL functions rand() and srand(). What exactly is rand()? The C++ STL's built-in rand() function is defined in the...

3 minutes read.

C++ if-else

C++ if else Control Statement if else control statement in C++ is used to control the program flow in a two-way direction. When condition returns a true value, then the program executes if condition block otherwise...

1 minute read.

Data Hiding in C++

C++ : High-performance apps can be made using the cross-platform language C++. Bjarne Stroustrup created C++ as an addition to the C language. Programmers have extensive control over memory and system...

3 minutes read.

Palindrome using Do-while loop in C++

What is Palindrome? A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++...

5 minutes read.