Advantages of Using Generics in Java with Examples


The two main advantages of using Genetics in Java are,


1. Type Safety:

    When we use Generics, we force our code to follow stronger type checks at compile time. So all the errors that could come up during Runtime are converted into Compile time errors, thus making your code less prone to errors in production.


2. Eliminating Type Casting:

    Once we introduce type safety using generics, the need for casting is eliminated, we can see this as a byproduct of type safety.


Let us look at both of the advantages with the help of a few examples.


    Example 1: No Type Safety causing Runtime Exception

    List list = new ArrayList();
    list.add(20);
    
    String name = (String) list.get(0);
    System.out.println(name);
    Output:

    Exception in thread "main" java.lang.ClassCastException:
    class java.lang.Integer cannot be cast to class java.lang.String


    Example 2: Introducing Type Casting

    List<String> list = new ArrayList<>();
    list.add(20);
    
    String name = (String) list.get(0);
    System.out.println(name);
    Compliation Error:

    java: incompatible types: int cannot be converted to java.lang.String

    Type Safety and Compliation Error

    Example 3: Type Casting leading to bugs fix at an early stage of development

    List<String> list = new ArrayList<>();
    list.add("Mike");
    
    String name = (String) list.get(0);
    System.out.println(name);
    Output:

    Mike


    Example 4: Elimination of the need for Type Casing

    List<String> list = new ArrayList<>();
    list.add("Mike");
    
    String name = (String) list.get(0);
    System.out.println(name);
    Output:

    Mike




This is not an AI-generated article but is demonstrated by a human running Java JDK 21 on an M1 Mac running macOS Sonoma 14.0.

Please support independent contributors like Code2care by donating a coffee.

Buy me a coffee!

Buy Code2care a Coffee!

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap