×

Why are generics used in Java

Java has a feature called generics that allows you to make a class, interface, and function accepting any (reference) type as a parameter. In other words, it is the idea that lets users to dynamically select the reference type that a function or class function Object() { [native code] } takes.

Java Generics is a group of related types or a group of related methods. Integer, String, and even user-defined types may be provided as parameters to classes, methods, and interfaces thanks to generics. Usually, classes like HashSet or HashMap utilize generics.

Making a class generic provides it type-safe, ensuring it can function with any datatype. Let's look at an example to help us understand generics.

In the following Java example we are defining a class named Employee whose constructor (parameterized) accepts an Integer object. While instantiating this class you can pass an integer object

class Employee{
   Integer id;
   Employee(Integer id){
      this.id = id;
   }
   public void display() {
      System.out.println("Value of id: "+this.id);
   }
}
public class ExampleofGenerics {
   public static void main(String args[]) {
      Employee std = new Employee(1432);
      std.display();
   }
}

Output:

Why are generics used in Java

A compile time exception results when passing any other object to the function Object() of this class.

public static void main(String args[]) {
   Employee std = new Employee("25");
   std.display();
}

Compile time errorCompile

ExampleofGenerics.java:12: error: incompatible types: String cannot be converted to Integer
   Employee std = new Employee("1432");
                              ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

Employee ids can be supplied as (an object of) String values, Float values, Double values, etc. You must modify the function Object() if you wish to provide a value from another object.

class Employee{
   String id;
   Employee(String id){
      this.id = id;
   }
}
Or,
class Employee{
   Float id;
   Employee(Float id){
      this.id = id;
   }
}

They are referred to as parameterized types when you specify generic types since they may interact with any datatype. Generics do not support the usage of basic datatypes.

Creating generic types

To use generic parameter T or, GT as the basis for a generic type class

class Employee <T>{
   T obj;
}

Where T (generic argument) stands for the datatype of the object you can supply to the function Object() of this class. During the compilation process, this will be decided.

You can or should select the type of the generic argument as when instantiating the class.

Employee<Float> obj = new Employee<Float>();

We may use generics to rephrase the above example as:

GenericsExample.java

class Employee<T>{
   T id;
   Employee(T id){
      this.id = id;
   }
   public void display() {
      System.out.println("Value of id: "+this.id);
   }
}
public class GenericsExample {
   public static void main(String args[]) {
      Employee<Float> std = new Employee<Float>(1432.5f);
      std.display();
   }
}

Output

Why are generics used in Java

Now, while creating an instance of the Employee class, you may supply a parameter specifying the type of object you want.

GenericsExample.java

class Employee<T>{
   T id;
   Employee(T id){
      this.id = id;
}
   public void display() {
      System.out.println("Value of id: "+this.id);
   }
}
public class GenericsExample {
   public static void main(String args[]) {
      Employee<Float> ep1 = new Employee<Float>(1432.5f);
      ep1.display();
      Employee<String> ep2 = new Employee<String>("1432");
      ep2.display();
      Employee<Integer> ep3 = new Employee<Integer>(1432);
      ep3.display();
   }
}

Output

Why are generics used in Java

Why are generics necessary?

The following benefits come from using generics in your code:

  • When you utilise types (ordinary objects), it normally results in an error at runtime if you supply the wrong object as a parameter. Type checking at build time prevents this from occuring.
  • While using generics, the problem will occur during compilation and is simple to fix.
  • Code reuse: By utilising generic types, you may define a method, class, or interface once and use it several times with different arguments.
  • You must cast the object and utilise it for a number of formal kinds. The majority of the time, generics allow you to provide an object of the needed type directly without the need for casting.
  • Generic classes allow you to create a variety of generic algorithms

Java Generics Types

Generic method: Generic Java methods accept an argument and execute an operation before returning some result. It functions precisely like a regular function, except generic methods have type arguments that are listed according to the actual type. This enables a broader use of the generic technique. Because the compiler handles type safety, programmers may write code more quickly because they are not required to do time-consuming, individual type casts.

Generic classes: A generic class has the exact same implementation as a non-generic class. The presence of a type parameter section is the only variation. There may be different parameter types, each separated by a comma. Parameterized classes or parameterized types are classes that take one or more parameters.


Related Topics

Java Database Connectivity with MySQL

In this tutorial, we will learn how to connect Database with MySQL in Java. 5 Steps to Connect to the Database in Java Load the driver (or) Register the driver classEstablish a...

4 minutes read.

How to Convert String to char in Java

How to Convert String to char in Java There are two methods to convert String to char are: Using charAt() method Using tocharArray() method Using charAt() method This is the method of String class that...

3 minutes read.

Bouncy Number in Java

We will define bouncy numbers in this section and write Java programmes to determine whether a specific number is bouncy. Java coding exams and academic assignments usually inquire about the...

3 minutes read.

Packages in Java

Packages in Java can be defined as an assortment for grouping various classes and interfaces based on their performance. It is a catalog for holding various java files. They provide...

4 minutes read.

Java Swing

Java Swing is the extension of Abstract Windows Toolkit (AWT). Any component designed in Swing will appear the same on any platform. Problems/Disadvantage of Abstract Windows Toolkit (AWT): As we know that...

27 minutes read.

Difference between next() and nextline() in Java

One of the simplest methods for receiving input of the basic data types, also including int, double, and strings, in Java, is to use the Scanner class, which is part...

3 minutes read.

Java StringWriter Class

The StringWriter class is a character stream in which it is used to store the output consisting of characters into the string buffer. Upon collecting output into a string buffer,...

3 minutes read.

Java Swings

Swing is a Java Foundation Class library and an extension to the Abstract Window Toolkit (AWT) (JFC).As compared to AWT, Swing has significantly better functionality, new components, increased component features,...

9 minutes read.

How to Convert String to float in Java

How to Convert String to Float in java It is used if you want to perform mathematical operations on the string that contains float number. You can convert String to float...

3 minutes read.

Java Logo

Java is a prominent and extensively used object-oriented programming language. In 1995, Sun Microsystems created it. Later in 2009, Oracle Corp takeover Java. History of Java Logo The name of the island...

3 minutes read.

What is String in Java?

What is String in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a Java...

4 minutes read.

Java Subtract Days from Current Date

Dealing with date and time in Java is not a particularly challenging operation because Java has an API for date and time that simplifies duties for developers. There are two...

3 minutes read.

Check whether Java is installed or not

As we know that there are various operating systems, to check whether Java is installed or not in Windows and Mac we use the following ways.           Windows Operating System: There are several...

2 minutes read.

How to Return Value from Lambda Expression Java?

What is Lambda Expression in Java? In Java 8, Lambda Expressions were introduced.A lambda expression is a brief section of code that accepts input and outputs a value. Similar to methods,...

4 minutes read.

Java String vs StringBuffer

Java String vs StringBuffer In this section, we will discuss the key differences between String and StringBuffer class. Before moving to the ahead in this section, let’s introduce with both classes. String...

4 minutes read.

Display List of TimeZone with GMT and UTC in Java

It is vital to establish the right TimeZone in Java code when working with dates for Daylight Saving Time. In this part, we will present the time zones with GMT. TimeZone Those...

5 minutes read.

Client Server Program in Java

Client Server Program in Java The client and server are the two main components of socket programming. The client is a computer/node that request for the service and the server is...

7 minutes read.

Star Pattern Programs in Java

Star Pattern Programs in Java The star pattern programs in Java is the part of pattern programs in Java, which we discussed earlier. Right Triangle Star Pattern Filename: StarPatternExample.java public class StarPatternExample {              public static void...

4 minutes read.

Singleton Design Pattern in Java

In the singleton pattern, a class that only has one instance and offers a universal point of access is taken into consideration. It can also be defined in another way, a...

4 minutes read.

Java Default Keyword

The Default keyword in java programming language is used as access modifier.If any of the variable or the constructor or the methods or the classes are not assigned with the...

3 minutes read.