![]() |
VOOZH | about |
Java Generics enable you to write code that works with different data types while ensuring type safety at compile time.
Arrays in Java are type-safe, meaning they can only store elements of a specific type. For example, a String[] can hold only String objects and adding any other type causes a compile-time error.
Example: Assigning a non-String to a String[] causes a compile-time error.
Output:
Explanation:
It is not recommended to use a ArrayList without generics. If you accidentally add a different type, it won't cause a compile-time error, but the program may fail at runtime.
Example: Showing lack of type safety in non-generic ArrayList, requires explicit type casting and may cause runtime errors
Output:
Explanation:
In the case of the array at the time of retrieval, it is not required to perform any type casting.
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: Program to retrieves the first element, but no type is specified.
Output:
Explanation:
Example:
ArrayList<String> al = new ArrayList<String>();
al.add("Vivek Yadav");
al.add(10); // Compile-time error: incompatible types
Explanation:
At the time of retrieval, there's no need for type casting.
String name = al.get(0); // Safe and direct assignment
Example: Retrieve Arraylist element without type casting.
Output:
Explanation: Type casting is not required as it is a TypeSafe. That is through generic syntax we can resolve type casting problems.