Java MCQ: Which of the following is NOT a benefit of using Generics in Java?
Answer:
Explanation:
Generics in Java offer several benefits, including code reusability, type safety, and the elimination of explicit type casting. However, runtime type checking is NOT a benefit of Generics. Instead, Generics provide compile-time type checking, which ensures that type-related errors are caught early in the development process.
With Generics, you can create methods, classes, and interfaces that can operate on objects of various types while still maintaining strong type safety. This means that when you create a generic class or method, you can specify the type of data it can work with, and the compiler will enforce this type constraint. This eliminates the need for casting, which was common in pre-Generics Java, where collections would store Object
references, and developers had to cast objects to their expected types manually.
By enforcing type safety at compile-time, Generics help to reduce runtime errors, such as ClassCastException
, that could occur when the wrong type is cast. Additionally, code reusability is enhanced because the same generic class or method can be used with different types, reducing code duplication and improving maintainability.
In summary, Generics improve the robustness and flexibility of Java code by providing compile-time type safety and reducing the need for type casting, but they do not perform runtime type checking.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html