12 Java Generics Interview Q&As

Q1 What do you understand by the term type erasure with regards to generics?
A1. The term type erasure is used in Java generics. In the interest of backward compatibility, robustness of generics has been sacrificed through type erasure. Type erasure takes place at compile-time. So, after compiling List and List, both end up as List at runtime. They are both just lists.

after compilation becomes backward compatible without any angular brackets.

Java generics differ from C++ templates. Java generics (at least until JDK 8), generate only one compiled version of a generic class or method regardless of the number of types used. During compile-time, all the parametrized type information within the angle brackets are erased and the compiled class file will look similar to code written prior to JDK 5.0. In other words, Java does not support runtime generics.

Q2. Why do you need generics?
A2. Generics was introduced in JDK 5.0, and allows you to abstract over types. Without generics, you could put heterogeneous objects into a collection. This can encourage developers to write programs that are harder to read and maintain. For example,

As demonstrated above, without generics you can add any type of object to a collection. This means you would not only have to use “instanceof” operator, but also have to explicitly cast any objects returned from this list. The code is also less readable. The following code with generics is not only more readable,

but also throws a compile time error if you try to add an Integer object to list1 or a String object to list2.

Q3. What are the differences among?

– Raw or plain old collection type e.g. Collection
– Collection of unknown e.g. Collection<?>
– Collection of type object e.g. Collection<Object>

A3. 1) The plain old Collection: is a heterogeneous mixture or a mixed bag that contains elements of all types, for example Integer, String, Fruit, Vegetable, etc.

2) The Collection<object>: is also a heterogeneous mixture like the plain old Collection, but not the same and can be more restrictive than a plain old Collection discussed above. It is incorrect to think of this as the super type for a collection of any object types.

Unlike an Object class is a super type for all objects like String, Integer, Fruit, etc, List<Object> is not a super type for List<String>, List<Integer>, List<Fruit>, etc. So it is illegal to do the following:

Though Integer is a subtype of Object, List is not a subtype of List<Object> because List of Objects is a bigger set comprising of elements of various types like Strings, Integers, Fruits, etc. A List of Integer should only contain Integers, hence the above line is illegal. If the above line was legal, then you can end up adding objects of any type to the list, violating the purpose of generics.

3) The Collection<?>: is a homogenous collection that represents a family of generic instantiations of Collection like Collection<String>, Collection<Integer>, Collection<Fruit>, etc.

Collection<?> is the super type for all generic collection as Object[ ] is the super type for all arrays.

Number class hierachy

Number class hierachy

Q4. How will you go about deciding which of the following to use?

1) <Number>
2) <? extends Number>
3) <? super Number>

A4. Many developers struggle with the wild cards. Here is the guide:

1. Use the ? extends wildcard if you need to retrieve object from a data structure. That is read only. You can’t add elements to the collection.

2. Use the ? super wildcard if you need to add objects to a data structure.

3. If you need to do both read and add elements, don’t use any wildcard.

Q5. What does the following code fragment print?

A5 It prints “true” because of type erasure(i.e. Rule 1), all instances of a generic class have the same runtime class, regardless of their actual type parameter. This also mean, there is no sense in checking generic information at runtime. The following code is illegal.

Q6. Is the following line legal? If not, how will you fix it?

A6. It is Illegal because Unlike an Object class is a super type for all objects like String, Integer, Fruit, etc, List&l;tObject> is not a super type for List<String>, List<Integer>, List<Fruit>, etc. List<?> is the super type.

Note:<? extends Number> is read only and <?> is almost read only allowing only removce( ) and clear ( ) operations.

The Collection<?> can only be used as a reference type, and you cannot instantiate it.

Q7. How will you generify your own Java class?

If you decompile the converted class file, you will get,

If you closely examine the above code, you would notice that the compiler has performed auto-boxing as generics does not support primitive types. The angle brackets have been removed for val1 & val2 declarations and appropriate castings have been added to convert from type T to Integer and Long types.

Q8. What do you understand by the term type argument inference?
A8. The type inference happens when the compiler can deduce the type arguments of a generic type or method from a given context information. There are 2 situations in which the type argument inference is attempted during compile-time.

1. When an object of a generic type is created as demonstrated in the MyGenericClass<T>.

2. When a generic method is invoked. For example,

The copy(…) method ensures that fruits from a mixed fruit basket cannot be copied to a basket that only holds oranges or mangoes. But a mixed fruit basket allows fruits to be copied from any basket.

Q9. Is the following code snippet legal? If yes why and if not why not?

A9. It is not legal as new T( ) will cause a compile-time error. This is partially because there’s no guarantee that the target class for raw type “T” has a constructor that takes zero parameters and partially due to type erasure where the raw type “T” does not have any way of knowing the type of object you want to construct at runtime.

Q10. Is it possible to generify methods in Java?
A10. Yes.

Note: If you had used the wildcard List<?> instead of List<T> on line A, it would not have been possible to add elements. You will get a compile-time error. So how does the compiler know the type of “T”? It infers this from your use of the method. The generated class file looks pretty much the same as the source file without the <Integer> and <String> angle brackets

Q11. Does the following code snippet compile? What does it demonstrate?

A11. Yes, the above code snippet does compile. It demonstrates that the type parameter in the class name and the type parameter in the method are actually different parameters. The method signature,

really means,

Q12. Can you identify any issues with the following code?


Line 4 will cause compile-time error on line 6 as the iterator is not generic. To fix this, replace line 4 with:

or add an explicit cast to line 6.

The fix 1 is preferred. When you get an iterator, keyset, or values from a collection, assign it to an appropriate parametrized type as shown in fix 1.

300+ Core Java Interview Q&As
Module 1 Java Overview+
Unit 1 17 Java Overview Interview Q&As  - Preview
Unit 2 4 Java Compile-time Vs Runtime Interview Q&As  - Preview
Module 2 Java data types+
Unit 1 8 Java data types interview Q&As  - Preview
Unit 2 7 Java primitives & objects memory consumption Q&As  - Preview
Unit 3 4 Java autoboxing & unboxing interview Q&As  - Preview
Unit 4 12 Java String class Interview Q&As  - Preview
Module 3 Java modifiers, annotations, initializers & constructors+
Unit 1 6 Java Modifiers every interviewer seems to like  - Preview
Unit 2 10 Java initializers, constructors, regular methods and static factory methods Q&As
Unit 3 8 Java Annotations interview Q&As
Unit 4 4 Java annotation types & processing interview Q&As
Module 4 Java classes, interfaces & class loaders+
Unit 1 12 Java classes and interfaces interview Q&As
Unit 2 3 Abstract classes Vs interfaces interview Q&As
Unit 3 3 Java class loading interview Q&As to ascertain your depth of Java knowledge
Module 5 Java Objects Interview Q&As+
Unit 1 5 Java Object class methods interview Q&As  - Preview
Unit 2 3 Object wait( ) & notify( ) interview Q&As
Unit 3 7 Object equals Vs == and pass by reference Vs value interview Q&As
Unit 4 10 Java immutable objects interview Q&As
Unit 5 10 Java serialization, cloning, and casting interview Q&As
Module 6 OOP & FP+
Unit 1 10 Java OOP Interview Q&As
Unit 2 5 Inheritance Vs Composition OOP Interview Q&As  - Preview
Unit 3 2 Polymorphism OOP Interview Q&As
Unit 4 8 OOP Design principles interview Q&As
Unit 5 5 OOP Vs FP, FP concepts & where to use FP Q&As  - Preview
Unit 6 19 Java Functional Programming (i.e. FP) interview Q&As
Unit 7 Java FP Lambda expressions by examples
Module 7 Generics & Java Collection Framework(JCF)-
Unit 1 12 Java Generics Interview Q&As  - Preview
Unit 2 5 Java Generics Wildcards Interview Q&As
Unit 3 17 Java Collection Framework (JCF) interview Q&As
Unit 4 9 Java data structures interview Q&As
Unit 5 4 Sorting objects in a Collection interview Q&As
Unit 6 8 Java Map interface & Caching interview Q&As
Unit 7 Lambda expressions to work with Java 8 Collections
Module 8 Java multithreading+
Unit 1 17 Java multi-threading interview Q&As  - Preview
Unit 2 7 Java locks & synchronized keyword interview Q&As
Unit 3 9 blocking, scheduling & daemon threads interview Q&As
Unit 4 7 Java Executor framework Interview Q&As
Unit 5 ExecutorService Vs Fork/Join & Future Vs CompletableFuture Interview Q&As
Unit 6 7 Java ThreadLocal interview Q&As
Unit 7 Java Thread stop, resume, suspend & interrupt interview Q&As
Unit 8 12 Java multi-threading differences between X and Y Q&As
Unit 9 Java multi-threading 15 scenarios interview Q&As
Module 9 What is wrong with this multithread code?+
Unit 1 5 Ways to debug Java thread-safety issues  - Preview
Unit 2 Heap Vs Stack, Thread safety & Synchronization  - Preview
Unit 3 Deep Vs Shallow comparison & multithreading
Unit 4 An excellent written test multithreading question - wait/notify
Unit 5 Multithreading & Locks
Unit 6 Java Collection & ConcurrentModificationException
Unit 7 HashMap & Race condition
Unit 8 ConcurrentHashMap & Atomic operations
Unit 9 JConsole for debugging deadlocks in Java
Unit 10 jvisualvm to debug deadlocks in Java
Module 10 Exceptions Handling+
Unit 1 5 Java exception handling interview Q&As
Module 11 Java I/O & NIO+
Unit 1 15 Java old I/O and NIO (i.e. New I/O) interview Q&As
Unit 2 Java 8 way to reading files
Module 12 JVM+
Unit 1 11 JVM memory model and Atomicity, Visibility, and Ordering interview Q&As
Unit 2 8 Java Garbage Collection interview Q&As to ascertain your depth of Java knowledge
Unit 3 jvisualvm to sample Java heap memory
Unit 4 5 JMX and MBean interview Q&As
Module 13 What is new?+
Unit 1 Java 7 features list
Unit 2 Java 8 features list
Module 14 Java code quality+
Unit 1 How will you go about improving on the following Java code?
Unit 2 How will you go about ensuring code quality in Java apps?
Unit 3 5 Java unit testing interview Q&As
Unit 4 Mocks, stubs, domain, and anemic objects interview Q&As
Unit 5 30+ Java Code Review Checklist Items
Module 15 Debugging Java applications+
Unit 1 7 debugging Java interview questions & answers
Unit 2 Debugging "NoSuchMethodError" in Java
Unit 3 Debugging JAR hell issues in Java
Unit 4 Debugging Java version issues
Unit 5 Remote debugging in Java with Java Debug Wire Protocol (JDWP)
Unit 6 Debugging like a pro with eclipse IDE tutorial for Java developers
Module 16 Performance considerations & memory management+
Unit 1 4 Java application performance considerations interview Q&As
Unit 2 8 Java memory management interview Q&As
Unit 3 jvisualvm to detect memory leak
Module 17 Design Patterns Interview Q&As+
Unit 1 12 Java design patterns interview Q&As
Unit 2 5 Java singleton design pattern interview Q&As
Unit 3 Java Proxy, Decorator, Adapter, Bridge, and Facade design patterns Interview Q&As
Unit 4 3 Flyweight design pattern Interview Q&As to improve memory usage & performance
Learn by categories on the go...
Learn by categories such as FAQs – Core Java, Key Area – Low Latency, Core Java – Java 8, JEE – Microservices, Big Data – NoSQL, Architecture – Distributed, Big Data – Spark, etc. Some posts belong to multiple categories.