Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Generics Interview Questions and Answers

by Anuradha, on Mar 29, 2018 11:55:55 AM

Generics Interview Questions and Answers

Q1. What are Generics in Java?

Ans: 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 ClassCastException. 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.

Q2. What are Generic Methods?

Ans: 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[] { 4, 5, 32, 100, 303, 2002, 465 };

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;

}

}

Q3. Why Generics is required?

Ans: Generics helps finding issues during compile time rather than runtime. Generics are parameter for types.

Q4. What are generics in c#?

Ans: 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.

Q5. What are concepts introduced with Java 5?

Ans: Generics , Enums , Autoboxing , Annotations and Static Import.

Q6. Example of a Bounded generic method.

Ans: static <T extends Number> T processTheNumber(T number){

T result = number;

return result;

}

Q7. Why won't the following code sample compile and how would you fix it?

Ans: 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

Q8. What are generic types? How are they declared and instantiated?

Ans: 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.

Q9. What is the difference between formal parameter and type parameter?

Ans: 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.

Q10. Is it legal to initialize List like this?

Ans: LinkedList<Integer> l=new LinkedList<int>();
No, Generic parameters cannot be primitives.

Q11. Generics.

Ans: 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.

 

Q12. What is type erasure?

Ans: 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.

Q13. How do you create sub-classes of generic classes?

Ans: 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.

Q14. Which of the following syntax is correct?

Ans: import static java.lang.System.*;
or
static import java.lang.System.*;

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

Q15. Explain Generics using a sample code.

Ans: 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.

Q16. 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.

Ans: 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.

Q17. Can Java generics be applied to primitive types?

Ans: No Java generics cannot be applied to primitive types. But you can use wrapper classes of primitive type to use Java generics.

Q18. Which of the following syntax are correct?

  1. LinkedList<Integer> l=new LinkedList<int>();
  2. List<Integer> l=new LinkedList<int>();
  3. LinkedList<Integer> l=new LinkedList<Integer>();
  4. List<Integer> l = new LinkedList<Integer>();

Ans: c and d are correct.

Q19. How can you suppress unchecked warning in Java ?

Ans: using @SuppressWarnings("unchecked") annotation.

@SuppressWarnings("unchecked")

List<String> myList = new ArrayList();

Q20. Can you create instances of generic type parameters?

Ans: No you cannot create instances of generic type parameters.

Topics:Generics Interview Questions and AnswersInformation Technologies (IT)

Comments

Subscribe

Top Courses in Python

Top Courses in Python

We help you to choose the right Python career Path at myTectra. Here are the top courses in Python one can select. Learn More →

aathirai cut mango pickle

More...