Java generics

Java Generics

In this Tutorial, we will learn about generics in Java. Generics Java was first introduced in Java5. Now it is one of the most profound feature of java programming language. Generic Java programming enables the programmer to create classes, interfaces and methods in which type of data is specified as a parameter. It provides a facility to write an algorithm independent of any specific type of data. Generics also provide type safety. Type safety means ensuring that an operation is being performed on the right type of data before executing that operation.

Using Generics, it has become possible to create a single class ,interface or method that automatically works with all types of data(Integer, String, Float etc). It has expanded the ability to reuse the code safely and easily.

Java generic methods help the user to specify a set of related methods using a single method declaration. The user can also specify a set of relatable objects using a single class declaration. Generics in java help in ensuring compile-time safety which helps the programmers to catch invalid arguments during the time of compilation.

Types of Java Generics

Generic Method: Generic Java method takes a parameter and returns some value after performing a task. It is exactly like a normal function, however, a generic method has type parameters that are cited by actual type. This allows the generic method to be used in a more general way. The compiler takes care of the type of safety which enables programmers to code easily since they do not have to perform long, individual type castings.

Generic Classes: A generic class is implemented exactly like a non-generic class. The only difference is that it contains a type parameter section. There can be more than one type of parameter, separated by a comma. The classes, which accept one or more parameters, ​are known as parameterized classes or parameterized types

  • All the generic methods include a type parameter section with < > brackets which precede the type of method.
  • Each type parameter section has another section that contains one or more type parameters. We separate these parameters by commas. It will specify a generic type name in the program.
  • We use the parameters for the return type. They behave like placeholders for all the arguments passed in the generic methods. These arguments are also known as actual type arguments.
  • There’s no difference between declarations of generic method’s body. However, the generic type can only represent the reference type and not the primitives such as double, char etc

What are the advantages of generics in Java

Generic class in java enables the use of classes and interfaces to themself turn into parameters. The user performs it while creating other classes or interfaces. The user can reuse the same code multiple times with different inputs with the help of generics.

The class helps to hold a single type of object as it cannot store multiple object types. There is no need for type casting while using generics. Otherwise, we always needed to typecast when not using generics. A good programming strategy suggests the problems should be handled during the compile-time only. So in generics, the issues are checked at the time of compilations, hence there is no scope of any error during the run time.

There’s the use of (?) symbol in generics which means a wildcard element. Wildcard element promotes any type. It is not allowed to use a wildcard as a type argument for a generic method but we can use it as a type of parameter, a field or return type.

Generics Class Syntax :

class Gen<G>{  
G obj;  
void add(G obj){this.obj=obj;}  
G get(){
return obj;}  
} 

In this syntax, the type G in generic class represents that it can refer to any string, int, or employee type. We use the specified type to store and retrieve data.

The classes ate denoted in the following manner:

T – Type

E – Element

K – Key

N – Number

V – Value

Generic Class Code :

public class Developerhelps{
public static < E > void printArray( E[] inputArray ) {
for(E element : inputArray) {
System.out.print(element+" ");
}
System.out.println();
}
public static void main(String args[]) {
Integer[] intArray = { 10, 20, 30, 40, 50 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'M', 'E', 'G', 'H', 'A' };
System.out.println("IntArray contains:");
printArray(intArray);  
System.out.println("doubleArray contains:");
printArray(doubleArray);   
System.out.println("charArray contains:");
printArray(charArray);  
}
}


Output :

intArray contains:
10 20 30 40 50 

doubleArray contains:
1.1 2.2 3.3 4.4 

charArray contains:
M E G H A

Generics Method

You can also create generic methods that can be called with different types of arguments. Based on the type of arguments passed to generic method, the compiler handles each method.

The syntax for a generic method includes a type-parameter inside angle brackets, and should appear before the method’s return type.

<type-parameter> return_type method_name (parameters) {…}

Generic Method Code :

public class Demo
{
  static <V, T> void display (V v, T t)
  {
    System.out.println(v.getClass().getName()+" = " +v);
    System.out.println(t.getClass().getName()+" = " +t);
  }
  public static void main(String[] args)
  {
    display(88,"This is string");
  }
}


Output :

java lang.Integer = 88
java lang.String = This is string

https://www.developerhelps.com/contact/

One comment on “Java Generics

Leave a comment

Your email address will not be published. Required fields are marked *

Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

Java Online Quiz

Level up your coding skills with our interactive programming quiz!