Loading

Q1. What is the purpose of Generics in Java?

Generics allow type-safe programming by enabling classes, interfaces, and methods to operate on objects of various types while providing compile-time type checking.






Q2. What are the advantages of using Generics in Java?
  • Type safety Prevents runtime type errors.
  • Code reusability Same code can handle multiple types.
  • Eliminates explicit typecasting Cleaner and safer code.
  • Improved readability and maintainability.





Q3. What are bounded type parameters in Generics?

Bounded types restrict the type parameter to a specific superclass or interface.
Example: T extends Number means the generic type can only be a subclass of Number.






Q4. What is the difference between ? extends T and ? super T in Generics?
  • ? extends T Upper bounded wildcard; allows reading objects of type T or its subclasses.
  • ? super T Lower bounded wildcard; allows writing objects of type T or its subclasses.





Q5. Can Generics work with primitive types in Java? Why or why not?

No. Generics require reference types, not primitives. For primitive types, their corresponding wrapper classes (Integer, Double, etc.) must be used.