Open In App

Type-Safety and Type-Casting in Java Generics

Last Updated : 07 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. It is possible to create classes that work with different data types using Generics. An entity such as a class, interface, or method that operates on a parameterized type is a generic entity. The main objective of Generics is to provide Type-Safety and to resolve Type-Casting problems.

1. Type-Safety

Arrays are always type-safe that is we can give the guarantee for the type of elements present inside the array. For example, if our programming requirement is to hold String type of objects it is recommended to use String array. In the case of a string array, we can add only string type of objects by mistake if we try to add any other type we will get compile time error.

Example:

Java




/*package whatever //do not write package name here */
  
import java.io.*;
  
class GFG {
    public static void main (String[] args) {
      String name[] =new String[500];
      name[0] = "Vivek Yadav";
      name[1] = "Ravi";
      name[2] = new Integer(100); 
    }
}


Output:

 

Explanation:

CompileTimeError: incompatbile types found: java.lang.Integer required: java.lang.String

That is we can always provide a guarantee for the type of elements present inside the array and hence arrays are safe to use with respect to the type that arrays are type-safe. But collections are not type-safe that is we can’t provide any guarantee for the
type of elements present inside the collection. For example, if our programming requirement is to hold only string type of objects
it is never recommended to go for ArrayList. By mistake, if we are trying to add any other type we won’t get any compile time
error but the program may fail at runtime.

Example:

Java




/*package whatever //do not write package name here */
  
import java.io.*;
  
class GFG {
    public static void main (String[] args) {
      ArrayList al =new ArrayList();
      al.add("Vivek Yadav");
      al.add("Ravi");
      al.add(new Integer(10));
  
      String name1 = (String)al.get(0);
      String name2 = (String)al.get(1);
      String name3 = (String)al.get(2);
    }
}


Output:

 

Explanation:

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

Hence we can’t provide a guarantee for the type of elements present inside collections that is collections are not safe to use with respect to type.

2. Type-Casting

In the case of the array at the time of retrieval, it is not required to perform any type casting. 

Java




/*package whatever //do not write package name here */
  
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        String name[] = new String[500];
        name[0] = "Vivek Yadav";
        name[1] = "Ravi";
        name[2] = new Integer(100);
    }
}


Output:

 

Explanation: Here type casting is not required. But in the case of collection at the time of retrieval compulsory, we should perform type casting otherwise we will get compile time error.

Example:

Java




/*package whatever //do not write package name here */
  
import java.io.*;
  
class GFG {
    public static void main (String[] args) {
        ArrayList al =new ArrayList();
        al.add("Vivek Yadav");
        al.add("Ravi");
        String name1= al.get(0);
    }
}


Output:

 

Explanation:

CompileTimeError: incompatible types : found : java.lang.Object
required:  java.lang.String
String name1=(String) al.get(0); // At the time of retrieval type casting is madantory

That is in collections type casting is a bigger headache. To overcome the above problems of collections(type-safety, type casting). Sun people introduced the generics concept in 1.5v hence the main objectives of generics are:

  1. To provide type safety to the collections.
  2. To resolve type casting problems.

To hold only string type of objects we can create a generic version of ArrayList as follows.

ArrayList<String> al =new ArrayList<String>();
al.add("Vivek Yadav");
al.add(10); // CompileTimeError: can't find symbol
incompatible type: required java.lang.String found: int

For this ArrayList we can add only string type of objects by mistake if we are trying to add any other type we will get compile time error that is through generics we are getting type safety. At the time of retrieval it is not required to perform any type casting we can
assign elements directly to string-type variables.

Example:

Java




/*package whatever //do not write package name here */
  
import java.io.*;
  
class GFG {
    public static void main (String[] args) {
      ArrayList<String> al =new ArrayList<String>();
      al.add("Vivek Yadav");
      String name =al.get(0);
      System.out.println("GFG!");
    }
}


Output:

 

Explanation: Type casting is not required as it is a TypeSafe. That is through generic syntax we can resolve type casting problems.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads