Java Generics Interview Questions

Generic interview questions in Java interviews are getting more and more common with Java 5 around there for considerable time and many application either moving to Java 5 and almost all new java development happening on Tiger(code name of Java 5). Importance of Generics and Java 5 features like Enum, Collection utilities are getting more and more popular on Java interviews. Generic interview question can get real 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 Generics interview is to try simple program best on various features of generics. Anyway In this Java interview article we will see some popular interview questions and there answers around generics in Java.

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

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

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

This is one of better interview question in Generics. Generics is implemented using Type erasure, 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 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 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 super class of T. for Example List<? extends Number> can accept List<Integer> or List<Float> . see more on above link.

5. How to write a generic method which accepts generic argument and return Generic Type?

writing 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:
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 previous Java generics interview question. Instead of asking to write Generic method Interviewer may ask to write a type safe class using generics. again key is instead of using raw types you need to used 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 Unit 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 most simple generics interview question in Java, if you know the fact that Array doesn’t support Generics and that’s why Joshua bloach suggested to prefer List over Array because List can provide compile time type-safety over Array.

10. How can you suppress unchecked warning 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.
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 any interview or you are looking answer for any Generics interview question in Java then please post in comment section.

Reference: 10 Interview Questions on Java Generics for Programmer and Developers from our JCG partner Javin Paul at the Javarevisited blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

One Response to "Java Generics Interview Questions"

  1. enyibinakata says:

    T while List will accept any List with type super class of T. for Example List can accept List or List . see more on above link.

    Read more: http://www.javacodegeeks.com/2012/07/java-generics-interview-questions.html#ixzz20JCy7utN
    T while List will accept any List with type super class of T. for Example List can accept List or List . see more on above link.

    Please correct the above to ? super Number instead.

Leave a Reply


5 − = three



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close