Thursday, July 29, 2021

10 Interview Questions on Java Generics for Programmer and Developers

Generic interview questions in Java interviews are getting more and more common with Java 5 around there for a considerable time and many applications either moving to Java 5 and almost all new Java development happening on Tiger(code name of Java 5).  The importance of Generics and Java 5 features like Enum,  Autoboxing, varargs, and Collection utilities like CountDownLatch, CyclicBarrier, and BlockingQueue is getting more and more popular on Java interviews. Generic interview questions can get really tricky if you are not familiar with bounded and unbounded generic wildcards, How generics works internally, type erasure and familiarity with writing parametrized generics classes and methods in Java.

Best way to prepare for a Generics interview is to try simple program best on various features of generics. Anyway, In this Java interview article we will see some popular Java Generics interview questions and there answer. 

By the way, there are lot of material available in Javarevisited to better preparing for Java and J2EE interviews, you can prepare multi-threading and Collections using 15 thread interview question and Top 10 Java collection interview question along with several other questions answers articles on Spring, Struts, JSP and Servlet. 

If you are GUI developer and working in Java Swing technology then you can also check interview questions on Java Swing  mostly asked in Investment banks

Java Generics Interview Questions

Here is a list of frequently asked Generics concept interview questions from Java interviews

1. What is Generics in Java? What are the advantages of using Generics?

This is one of the first interview questions asked on generics in any Java interview, mostly at beginners and intermediate levels. Those who are coming from prior to Java 5 background know that how inconvenient it was to store object in Collection and then cast it back to the correct Type before using it. Generics prevent those. it provides compile time type-safety and ensures that you only insert the correct Type in collection and avoids ClassCastException in runtime.



2. How Generics works in Java ? What is type erasure ?

This is one of the better interview question in Generics. Generics is implemented using Type erasure, the compiler erases all type related information during compile time and no type related information is available during runtime. for example List<String> is represented by only List at runtime. 

This was done to ensure binary compatibility with the libraries which were developed prior to Java 5. you don't have access to Type argument at runtime and Generic type is translated to Raw type by the compiler during runtime. you can get lot of follow up question based on this Generic interview question based upon your response e.g. Why Generics is implemented using Type erasure or presenting some invalid generic code which results in compiler error. read my post How Generics works in Java for more details



3. What is Bounded and Unbounded wildcards in Generics ?

This is another very popular Java interview questions on Generics. Bounded Wildcards are those which impose bound on Type. there are two kinds of Bounded wildcards <? extends T> which impose an upper bound by ensuring that type must be sub class of T and <? super T> where its imposing lower bound by ensuring Type must be super class of T. This Generic Type must be instantiated with Type within bound otherwise it will result in compilation error. On the other hand <?> represent and unbounded type because <?> can be replace with any Type. See more on my post differences between Bounded and Unbounded wildcards in Generics.



4. What is the difference between List<? extends T>  and  List <? super T>?

This is related to previous generics interview questions, some time instead of asking what is bounded and unbounded wildcards interviewer present this question to gauge your understanding of generics. Both of List declaration is example of bounded wildcards, List<? extends T> will accept any List with Type extending T while List<? super T> will accept any List with type superclass of T. for Example List<? extends Number> can accept List<Integer> or List<Float>. see more on the above link.



5. How to write a generic method that accepts a generic argument and returns a Generic Type?

Interview questions on Generics in Java 2 yearswriting generic method is not difficult, instead of using raw type you need to use Generic Type like T, E or K,V which are well-known placeholders for Type, Element and Key, Value. Look on Java Collection framework for examples of generics methods. In simplest form a generic method would look like this:

public V put(K key, V value) {
        return cache.put(key, value);
}



6. How to write parametrized class in Java using Generics?

This is an extension of the previous Java generics interview questions. Instead of asking to write a Generic method Interviewer may ask to write a type-safe class using generics. again the key is instead of using raw types you need to use generic types and always use standard place holder used in JDK.



7. Write a program to implement LRU cache using Generics?

This is an exercise for anyone who like Coding in Java. One hint is that LinkedHashMap can be used implement fixed size LRU cache  where one needs to remove eldest entry when Cache is full. LinkedHashMap provides a method called removeEldestEntry() which is called by put() and putAll() and can be used to instruct to remove eldest entry. you are free to come up with your own implementation as long as you have a written a working version along with JUnit test.



8. Can you pass List<String> to a method which accepts List<Object>

This generic interview question in Java may look confusing to any one who is not very familiar with Generics as in fist glance it looks like String is object so List<String> can be used where List<Object> is required but this is not true. It will result in compilation error. It does make sense if you go one step further because List<Object> can store any any thing including String, Integer etc but List<String> can only store Strings.

List<Object> objectList;
List<String> stringList;
     
objectList = stringList;  //compilation error incompatible types



9. Can we use Generics with Array?

This was probably the most simple generics interview question in Java, if you know the fact that Array doesn't support Generics and that's why Joshua Bloch suggested in Effective Java to prefer List over Array because List can provide compile-time type-safety over Array.


10. How can you suppress the unchecked warnings in Java?

javac compiler for Java 5 generates unchecked warnings if you use combine raw types and generics types e.g.

List<String> rawList = new ArrayList()
Note: Hello.java uses unchecked or unsafe operations.;

which can be suppressed by using @SuppressWarnings("unchecked") annotation.


Java Generics Interview questions Update:

I got few more interview questions on Generics in Java to share with you guys, These questions focus on What is the difference between Generics type and Raw type and Can we use Object in place of bounded wildcards etc:

Difference between List<Object> and raw type List in Java?

Main difference between raw type and parametrized type List<Object> is that, compiler will not check type-safety of raw type at compile time but it will do that for parametrized type and by using Object as Type it inform compiler that it can hold any Type of Object e.g. String or Integer

This Java Generics interview question is based on correct understanding of  raw type in Generics. Any way second difference between them is that you can pass any parametrized type to raw type List but you can not pass List<String> to any method which accept List<Object> it will result in compilation error. Read How Generics works in Java for more details.



Difference between List<?> and List<Object> in Java?

This generics interview question may look related to previous interview questions but completely different. List<?> is List of unknown type while List<Object> is essentially List of any Type. You can assign List<String>, List<Integer> to List<?> but you can not assign List<String> to List<Object>.

List<?> listOfAnyType;
List<Object> listOfObject = new ArrayList<Object>();
List<String> listOfString = new ArrayList<String>();
List<Integer> listOfInteger = new ArrayList<Integer>();
     
listOfAnyType = listOfString; //legal
listOfAnyType = listOfInteger; //legal
listOfObjectType = (List<Object>) listOfString; //compiler error - in-convertible types
            
to know more about wildcards see Generics Wildcards Examples in Java


Difference between List<String> and raw type List.

This Generics interview question is similar to the difference between raw type and parameterized type. Parametrized types are type-safe and type-safety will be guaranteed by compiler but List raw type is not type-safe. You can not store any other Object on List of String but you can not store any Object in raw List. There is no casting required in the case of Parametrized type with Generics but explicit casting will be needed for raw type.

List listOfRawTypes = new ArrayList();
listOfRawTypes.add("abc");
listOfRawTypes.add(123); //compiler will allow this - exception at runtime
String item = (String) listOfRawTypes.get(0); //explicit cast is required
item = (String) listOfRawTypes.get(1); //ClassCastException because Integer can not be cast in String
     
List<String> listOfString = new ArrayList();
listOfString.add("abcd");
listOfString.add(1234); //compiler error, better than runtime Exception
item = listOfString.get(0); //no explicit casting is required - compiler auto cast

These were some of the frequently asked generics interview questions and answers in Java. None of these generic interview questions are tough or hard, Indeed they are based on fundamental knowledge of generics. 

Any Java programmer who has decent knowledge of Generics must be familiar with these generics questions in Java. If you have any other good generic question which has been asked in an interview or you are looking answer for any Generics interview question in Java then please post in the comment section.


9 comments :

Anonymous said...

Small correction to your #5 - it won't compile the way it is shown(unless K & V are defined as classes, interfaces or enums).

It should be:
"
public <K, V> V put(K key, V value) {
...
}
"

Zams said...

One of the question asked in Generics is "How do you determine type of Object Generics variable is using at run-time"?
well this is nothing to do with Generics as Generics doesn't retain type information. all Type information erased by Type Erasure. but you can use class.getClass() to find type of Object at run-time.

Anonymous said...

@tech-drum i think so it would work:

public class Test{

public V put(K key, V value) {
.....
}
}

Unknown said...

public class Test{

public V put(K key, V value) {
.....
}
}

no it will not run.

Anonymous said...

listOfRawTypes.add(123); //compiler will allow this - exception at runtime

There will be no exception

Anonymous said...

item = (Integer) listOfRawTypes.get(1); // this will work though

Akash said...

Can you pass to a method which accepts List

Awesome question and your answer are really to simple.

http://www.javaaster.com

Struts2Spring2Hibernate3 said...

"public static void main(String[] args) {
//List l;
List o = new ArrayList();
String s = new String("kishor");
Integer i = new Integer(10);
o.add(s);
o.add(i);
System.out.println(o);



}"

This code is working fine and giving output as

[kishor, 10]

for List????

hossam said...

There are more than one error in your post, for example the generic method should be in this form
public V put(K key, V value)

so please stop posting information you are not totally sure of in order not to disguide people !!

Post a Comment