Core Java Interview Questions – Generics

This Core java interview questions-Generics post providing all the interview questions on Generics including the need to generics in the collection, why we cannot apply generics to arrays, how to apply generics and much more.

What is Generics in Java?
Used to restrict the data to be stored into Collection object.
Generics ensures that you only insert correct Type in the collection and avoids ClassCastException.

What are advantages of using Generics?
Generics prevents type casting while accessing elements from collection object.
It provides compile-time type-safety.

When generics introduced?
Generics are available since JDK 1.5

What are Bounded wildcards in Generics?
<? extends T> impose an upper bound.
<? super T> where its imposing lower bound.
This Generic Type must be instantiated with Type within bound otherwise it will result in compilation error.

Write a Generic method that receives generic argument and returns Generic Type?
public V fun(K key, V value)
return fun(key, value);

Can we use Generics with Array?
An array doesn’t support Generics because the array is already data restricted. It accepts only homogenous elements.

What happens if we don’t apply generics in collection program?
The compiler shows a warning message that “program used Unchecked or Unsafe operations”.

What is the command used to check generics warnings?
-Xlint command must be used to check these warning.

Can we run the application with suppress warnings of Generics?
Yes allowed, applying generics to java collection program is optional.

How to remove Generics warnings in the application?
Can be suppressed by using @SuppressWarnings(“unchecked”) annotation.

Why do we need generics in java?
Stronger type checks at compile time.
Elimination of casts.

>C Interview Questions on Pointers<

Share this