Iteanz Interview Questions | Latest Technologies Interview Questions

Generics Interview Questions and Answers

Written by Rupa.R | Sep 10, 2022 9:26:20 AM

1.What are Generics in Java?

Generics are a feature that allow a class to be parameterized into sub-types. Generics provide compile-time safety and prevent runtime typecasting errors resulting in Class Cast Exception. Without generics, a user is forced to use the lowest common base-class and then typecast the object, which is highly error-prone and has no type-safety.

2.What are Generic Methods?
Generic method are methods that is type parameterized.
public class GenericMethodExample {

public static void main(String[] s) {

String[] StrArray = new String[] { “Find”, “the”, “word”, “in”, “this”,

“Array” };

System.out.println(contains(StrArray, “word”));

Integer[] intArray = new Integer[] { 45321003032002465 };

System.out.println(contains(intArray, 2002));

}

public static <T> boolean contains(T[] list, T itemToFind) {

for (T listItem : list) {

if (itemToFind == null) {

if (listItem == null)

return true;

else if (itemToFind.equals(listItem)) {

return true;

}

}

return false;

}

}

3.Why Generics is required?
Generics helps finding issues during compile time rather than runtime. Generics are parameter for types.

4. What are generics in c#?
Generics refers to the technique of writing the code for a class without specifying the data type(s) that the class works on. It allow you to define type-safe data structures, without committing to actual data types. It allows writing less but more effective code and provides flexibility and power but the developer needs to be responsible while using it.

5. What are concepts introduced with Java 5 ?
Generics , Enums , Autoboxing , Annotations and Static Import.

6. Example of a Bounded generic method.
static <T extends Number> T processTheNumber(T number){

T result = number;

return result;

}

7. Why won’t the following code sample compile and how would you fix it?
This will raise a compilation error. It is incorrect to pass a List<String> to a method accepting List<Object>. A List<Object> can accept Strings, but t1 can only accept List<Object>.
Either ls should be changed to List<Object>, or lo should be made Generic: List<? extends Object> lo

8. What are generic types? How are they declared and instantiated?
A generic type is a generic class or interface that is parameterized over types.
Declaration of generic types – A generic class is declared using the format ‘class MyClass {…}’. The angle brackets <> is the type parameter section and specifies the type parameters T1, T2 … for the generic class.
Instantiation of generic types – You instantiate a generic class using the new keyword as usual, but pass actual types within the parameter section. Example – ‘MyClass myClass = new MyClass();’. In Java 7 and later you can eliminate the type and just have the angle brackets <>. Example – ‘MyClass myClass = new MyClass<>();’. The empty angular brackets <> syntax is commonly referred to as the Diamond

9. What is the difference between formal parameter and type parameter?
formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.

10. Is it legal to initialize List like this ?
LinkedList<Integer> l=new LinkedList<int>();
No, Generic parameters cannot be primitives.

11.Generics.
Generics introduced in Java 1.5, facilitates strong-typing on the collection objects. Generics defines the object types that the collection can hold.

It provides compile time type-safety and ensures that only the particular type is added in collection and eliminates ClassCastException in runtime.

12.What is type erasure?
The Type information used for Generic objects is only available at compile time. The compiler removes all the type information when converting to byte-code. This makes the type information unavailable at Runtime and the Generic type is converted to Raw type. The compiler provides checks at compile time to prevent runtime errors for incorrect type information.

The case where things can go wrong is when directly using Raw types in the code. The compiler will raise a warning in this case but it will not fail.

13. How do you create sub-classes of generic classes?
Similar to regular classes and interfaces, you can create sub-types of generic classes or interfaces by extending or implementing from the generic classes or interfaces.
For example, in Java collections API, ArrayList implements List and Listimplements Collections. The sub-type relation is preserved as long as the type argument does not vary. So, ArrayList implements List and List implements Collections

14. Which of the following syntax is correct ?
import static java.lang.System.*;
or
static import java.lang.System.*;

import static java.lang.System.*; is correct

15.Explain Generics using a sample code.
List list = new ArrayList();

list.add(“No Generics is used “);

String s = (String) list.get(0);

In the above example, ArrayList can hold any type of objects, however we need to cast each object to its appropriate data type since get method’s return type is Object. A string literal is added to the list and to get it from the list we need cast and store it.
If we store an employee object for example at the first index, then the 3rd line of code will throw a run-time Exception.

List<String> list = new ArrayList<String>();

list.add(“Generics is implemented”);

String s = list.get(0);   // no cast is required

In the above code, the example is rewritten using generics, and the list is strongly typed that requires no casting.

16. Is the code compile-time and run-time safe? What do I and K stand for? What is the use of the extends keyword in both places? Explain the get method definition. Explain the wildcard symbols.

class A<K, I extends List<K>> {

public K get(final int index, final I list) {

return list.get(idx);

}

}

class B extends A<String, LinkedList<String>> { }

Class C {

public static void main(String…args) {

A<Integer, ArrayList<Integer>> a = new A<>;

B b = new B();

A<?, ?> g;

A<? extends Integer, ?> f;

g = a;

g = b;

f = a;

}

}

Yes, this code is compile-time and run-time safe.

I and K are Generic type parameters used to ensure type safety.

The extends keyword in the first line defines the scope of the I parameter. The I parameter can only be a sub-type of List of type K. K by default extends Object.

The second extends keyword is used for inheriting class A and fixing the type parameters of A to String and LinkedList.

The get method takes an index integer and a List of type K as the parameters. It returns the list value at index, which will have a return type K because the list parameter is fixed to K.

For example, when get is called on instance b of class B, get will take a LinkedList<String> and return the String at index.

The wildcard symbols indicate that g can have any type within the bounds of the parameters. That is why a and b can be assigned to it. In the case of f, the first parameter gets limited to Integer sub-types, so only a can be assigned to it, not b. f can be assigned to g, but not the other way round.

17. Can Java generics be applied to primitive types?
No Java generics cannot be applied to primitive types. But you can use wrapper classes of primitive type to use Java generics.

18. Which of the following syntax are correct ?

a. LinkedList<Integer> l=new LinkedList<int>();
b. List<Integer> l=new LinkedList<int>();
c. LinkedList<Integer> l=new LinkedList<Integer>();
d. List<Integer> l = new LinkedList<Integer>();

c and d are correct.

19. How can you suppress unchecked warning in Java ?
using @SuppressWarnings(“unchecked”) annotation.

@SuppressWarnings(“unchecked”)

List<String> myList = new ArrayList();

20. Can you create instances of generic type parameters?
No you cannot create instances of generic type parameters.