Top 10 Java Generics Interview Questions and Answers

In this post, I will be sharing the frequently asked top 10 Java generics interview questions and answers for experienced professionals. Generics was introduced in Java 5. Generics is used for type safety and it automatically manages the casting during compilation. That helps developers write the code without worrying about Type-management. It is introduced to enhance or supplement the Java collections. But we can use those outside collections as well.

Top 10 Java Generics Interview Questions and Answers

Q1. How to create a Generic class in Java?


We can declare a class using the following syntax:

class MyClassGeneric<T>

Note: We can use any type parameter instead of T.


Q2. What are the different type parameters?

Type parameters are the keyword that we provide during declaring the class or method. There are totally different five commonly used type parameters:

• T – Type
• V – Value
• K – Key
• E – Element
• N – Number

You can use your own customized type parameters as well.


Q3. What is the purpose of generics in Java?

This is mostly the first question asked on Generics. Generics in Java are used to provide type safety and to allow developers to write code that can work with multiple types while still providing compile-time type checks. This helps to prevent runtime errors caused by type mismatches and allows for more efficient code, as the compiler can perform more optimizations when it knows the specific types being used. We can divide its usability into major three parts:

Type checking at Compile time - The Java compiler applies type checking to generic code at compile time and throes errors for type safety violations.

Removed the need for implicit casting - Java code that uses generics does not need explicit casting, whereas the code that is non-generic requires explicit casting.

Generic algorithms implementations - By using generics, programmers can develop generic algorithms designed to work on collections of different types that are type-safe and easier to use.


Q4. Can you use primitives with Java generics? If not, how do you work around this limitation?

It is not possible to use primitives with Java generics, as generics only work with reference types. To work around this limitation, you can use the wrapper classes for the corresponding primitive types, such as Integer for int, Double for double, etc. But arrays work with the primitives. This is one of the major differences between arrays and Typed ArrayList.


Q5. What is the difference between a raw type and a parameterized type in Java?

A raw type is a generic type without any type arguments, such as List. A parameterized type is a generic type with one or more type arguments, such as List<String> or ArrayList<Object>. Raw types are not recommended to use, as they can lead to runtime errors due to the lack of type safety. Raw types are still available in Java for backward compatibility but it is strictly recommended not to use the raw types.


Q6. Can you override a generic method with a non-generic one in Java? Can you override a non-generic method with a generic one?

You can override a generic method with a non-generic one in Java, as the non-generic method will have a more specific type than the generic one.

However, you cannot override a non-generic method with a generic one, as the generic method will have a less specific type than the non-generic one.


Q7. What is a wildcard in Java generics? Give an example of its usage.

A wildcard in Java generics is a placeholder for an unknown type. It is denoted with a question mark (?), and it can be used in situations where the exact type is not important or not known. For example, you might use a wildcard when declaring a method that accepts a list of any type, such as

public void printArrayList(ArrayList<?>  myList)

Wildcard can be also unbounded and bounded. Following is the example of an upper bounded wildcard

public int putCars(Collection<? extends Car> carsList)

The above method demonstrates the use of a bounded wildcard in the method parameter.


Q8. How do you create a generic array in Java?

To create a generic array in Java, you can use the following syntax:

// Create an array of a specific type
Type[] array = (Type[]) new Object[size];

// Create an array of a generic type
E[] array = (E[]) new Object[size];

Here, Type is the specific type that you want the array to hold, and E is the generic type parameter. The size parameter specifies the length of the array.

Keep in mind that this syntax is not the recommended way to create a generic array in Java, as it can cause a ClassCastException at runtime. A better way to create a generic array is to use a method that takes an array of the specific type as an argument and returns an array of the generic type, like this:

public static <T> T[] createArray(T[] array, int size) {
   return (T[]) Array.newInstance(array.getClass().getComponentType(), size);
}

// Usage:
String[] stringArray = createArray(new String[0], 10);

This method uses reflection to create a new array of the same type as the input array, but with a specified length.


Q9. How can you suppress unchecked warnings in Java?

We can suppress these warnings using the @SuppressWarning(“unchecked”) annotation. This is useful when we are manually casting the Object to other types.


Q10. How do you handle exceptions with generics in Java?

In Java, you can use generics to specify the types of exceptions that a method can throw. This allows you to specify a specific exception type or a group of exception types that the method can throw, which can be useful for documenting the expected behavior of the method and for handling exceptions in a more type-safe way.
Here's an example of how you can use generics to specify the exceptions that a method can throw:

public <T extends Exception> void doSomethingMethod() throws T {
   // Method body goes here
}

In this example, the method doSomething can throw any exception type that is a subclass of Exception.

You can also specify multiple exception types using the & operator, like this:

public <T extends Exception & Cloneable> void doSomethingMethod () throws T {
    // Method body goes here
}

This method can throw any exception type that is a subclass of Exception and implements the Cloneable interface.

When you specify the exception types that a method can throw using generics, you can catch those exceptions using a catch block that specifies the specific exception type, like this:

try {
   doSomethingMethod();
} catch (Exception e) {
   //Exception handling code goes here
}

This catch block will handle any exception that is thrown by the doSomething Method method and is a subclass of Exception.


That's all for today. Please mention in the comments if you have any questions related to the top 10 Java Generics interview questions and answers for experienced.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry