Generics In Java Interview Questions And Answers latest for experienced professionals from Coding Compiler. These Generics In Java interview questions were asked in various interviews conducted by top multinational companies across the globe. We hope that these interview questions on Java Generics will help you in cracking your job interview. All the best and happy learning
In this Interview Questions Blog, You are going to learn
- Generics In Java Interview Questions
- Generics in Java Interview Questions And Answers
- The Best Generics in Java Interview Questions And Answers
- Advanced Generics in Java Interview Questions And Answers
- Java Generics Interview Questions and Answers
Generics In Java Interview Questions
- What is Generics in Java ?
- How Generics works in Java ? What is type erasure?
- What is Bounded and Unbounded wildcards in Generics?
- Can the wildcard argument be bounded?
- How to write parametrized class in Java using Generics?
- What is bounded type parameter?
- What is wildcard in Java generic?
- What Is a Generic Type Parameter?
- How Does a Generic Method Differ from a Generic Type?
- What Is Type Erasure?
Generics in Java Interview Questions And Answers
Q1. What is Generics in Java ? What are advantages of using Generics?
Answer:
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.
Q2. How Generics works in Java ? What is type erasure?
Answer.
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.
Q3. What is Bounded and Unbounded wildcards in Generics ?
Answer.
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.
Q4. Can the wildcard argument be bounded?
Answer:
A wildcard can have only one bound, while a type parameter can have several bounds. A wildcard can have a lower or an upper bound, while there is no such thing as a lower bound for a type parameter.
Q5. How to write parametrized class in Java using Generics ?
Answer.
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.
Q6. What is bounded type parameter?
Answer:
There may be times when you’ll want to restrict the kinds of types that are allowed to be passed to a type parameter. … This is what bounded type parameters are for. To declare a bounded type parameter, list the type parameter’s name, followed by the extends keyword, followed by its upper bound.
Q7. What is wildcard in Java generic?
Answer:
Java Generic’s wildcards is a mechanism in Java Generics aimed at making it possible to cast a collection of a certain class, e.g A, to a collection of a subclass or superclass of A.
Q8. What Is a Generic Type Parameter?
Answer:
Type is the name of a class or interface. As implied by the name, a generic type parameter is when a type can be used as a parameter in a class, method or interface declaration.
Let’s start with a simple example, one without generics, to demonstrate this:
public interface Consumer {
public void consume(String parameter)
}
In this case, the method parameter type of the consume() method is String. It is not parameterized and not configurable.
Now let’s replace our String type with a generic type that we will call T. It is named like this by convention:
public interface Consumer<T> {
public void consume(T parameter)
}
When we implement our consumer, we can provide the type that we want it to consume as an argument. This is a generic type parameter:
public class IntegerConsumer implements Consumer<Integer> {
public void consume(Integer parameter)
}
In this case, now we can consume integers. We can swap out this type for whatever we require.
Q9. How Does a Generic Method Differ from a Generic Type?
Answer:
A generic method is where a type parameter is introduced to a method, living within the scope of that method. Let’s try this with an example:
public static <T> T returnType(T argument) {
return argument;
}
We’ve used a static method but could have also used a non-static one if we wished. By leveraging type inference (covered in the next question), we can invoke this like any ordinary method, without having to specify any type arguments when we do so.
Q10. What Is Type Erasure?
Answer:
It’s important to realize that generic type information is only available to the compiler, not the JVM. In other words, type erasure means that generic type information is not available to the JVM at runtime, only compile time.
The reasoning behind major implementation choice is simple – preserving backward compatibility with older versions of Java. When a generic code is compiled into bytecode, it will be as if the generic type never existed. This means that the compilation will:
Replace generic types with objects
Replace bounded types (More on these in a later question) with the first bound class
Insert the equivalent of casts when retrieving generic objects.
It’s important to understand type erasure. Otherwise, a developer might get confused and think they’d be able to get the type at runtime :
public foo(Consumer<T> consumer) {
Type type = consumer.getGenericTypeParameter()
}
The above example is a pseudo code equivalent of what things might look like without type erasure, but unfortunately, it is impossible. Once again, the generic type information is not available at runtime.
The Best Generics in Java Interview Questions And Answers
Q11. If a Generic Type Is Omitted When Instantiating an Object, Will the Code Still Compile?
Answer:
As generics did not exist before Java 5, it is possible not to use them at all. For example, generics were retrofitted to most of the standard Java classes such as collections. If we look at our list from question one, then we will see that we already have an example of omitting the generic type:
List list = new ArrayList();
Despite being able to compile, it’s still likely that there will be a warning from the compiler. This is because we are losing the extra compile-time check that we get from using generics.
The point to remember is that while backward compatibility and type erasure make it possible to omit generic types, it is bad practice.
Q12. How ConcurrentHashMap works in Java?
Answer:
partitions map into segments and lock them individually instead of locking the whole map.
Q13. What is PriorityQueue in Java?
Answer:
A data structure which always keeps the highest or lowest element at the head so that you can access or remove it in constant time.
Q14. What is generic method in Java?
Answers:
Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter’s scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.
Q15. What Are Advantages Of Using Generics?
Answer :
Advantage of Java Generics:
There are mainly 3 advantages of generics. They are as follows:
Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to store other objects.
Type casting is not required: There is no need to typecast the object.
Before Generics, we need to type cast.
List list = new ArrayList();
list.add(“hello”);
String s = (String) list.get(0);//typecasting
After Generics, we don’t need to typecast the object.
List<String> list = new ArrayList<String>();
list.add(“hello”);
String s = list.get(0);
Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The good programming strategy says it is far better to handle the problem at compile time than runtime.
List<String> list = new ArrayList<String>();
list.add(“hello”);
list.add(32);//Compile Time Error.
Q16. If The Compiler Erases All Type Parameters At Compile Time, Why Should You Use Generics?
Answer :
You should use generics because:
- The Java compiler enforces tighter type checks on generic code at compile time.
- Generics support programming types as parameters.
- Generics enable you to implement generic algorithms.
Q17. Write A Generic Method To Exchange The Positions Of Two Different Elements In An Array.
Answer :
public final class Algorithm
{
public static <T> void swap(T[] a, int i, int j)
{
T temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
Q18. Will The Following Class Compile? If Not, Why?
public Final Class Algorithm {
Public Static T Max(t X, T Y) {
Return X > Y ? X : Y;
}
}
Answer :
No. The greater than (>) operator applies only to primitive numeric types.
Q19. Write A Generic Method To Find The Maximal Element In The Range [begin, End) Of A List.
Answer :
import java.util.*;
public final class Algorithm {
public static <T extends Object & Comparable<? super T>>
T max(List<? extends T> list, int begin, int end) {
T maxElem = list.get(begin);
for (++begin; begin < end; ++begin)
if (maxElem.compareTo(list.get(begin)) < 0)
maxElem = list.get(begin);
return maxElem;
}
}
Q20. Given The Following Classes:
class Shape { /* … */ }
class Circle Extends Shape { /* … */ }
class Rectangle Extends Shape { /* … */ }
class Node { /* … */ }
will The Following Code Compile? If Not, Why?
node Nc = New Node<>();
node Ns = Nc;
Answer :
No. Because Node is not a subtype of Node.
Advanced Generics in Java Interview Questions And Answers
Q21. Can You Give An Example Of A Generic Method?
Answer :
A generic type can be declared as part of method declaration as well. Then the generic type can be used anywhere in the method (return type, parameter type, local or block variable type).
Consider the method below:
static <X extends Number> X doSomething(X number){
X result = number;
//do something with result
return result;
}
The method can now be called with any Class type extend Number.
Integer i = 5;
Integer k = doSomething(i);
Q22. Can We Use Generics With Array?
Answer :
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.
Q23. Can you give an example of how Generics make a program more flexible?
Answer.
Consider the class below:
class MyList {
private List<String> values;
void add(String value) {
values.add(value);
}
void remove(String value) {
values.remove(value);
}
}
MyList can be used to store a list of Strings only.
MyList myList = new MyList();
myList.add(“Value 1”);
myList.add(“Value 2”);
To store integers, we need to create a new class. This is problem that Generics solve. Instead of hard-coding String class as the only type the class can work with, we make the class type a parameter to the class.
Example with Generics
Let’s replace String with T and create a new class. Now the MyListGeneric class can be used to create a list of Integers or a list of Strings
class MyListGeneric<T> {
private List<T> values;
void add(T value) {
values.add(value);
}
void remove(T value) {
values.remove(value);
}
T get(int index) {
return values.get(index);
}
}
MyListGeneric<String> myListString = new MyListGeneric<String>();
myListString.add("Value 1");
myListString.add("Value 2");
MyListGeneric<Integer> myListInteger = new MyListGeneric<Integer>();
myListInteger.add(1);
myListInteger.add(2);
Q24. How do you declare a Generic Class?
Answer:
Note the declaration of class:Instead of T, We can use any valid identifier.
class MyListGeneric<T>
Q25. How can we restrict Generics to a super class of particular class?
Answer:
In MyListGeneric, Type T is defined as part of class declaration. Any Java Type can be used a type for this class. If we would want to restrict the types allowed for a Generic Type, we can use a Generic Restrictions. In declaration of the class, we specified a constraint “T super Number”. We can use the class MyListRestricted with any class that is a super class of Number class.
Q26. How can you suppress unchecked warning in Java ?
Answer:
using @SuppressWarnings(“unchecked”) annotation.
@SuppressWarnings(“unchecked”)
List<String> myList = new ArrayList()
Q27. Example of a generic method from JAVA Collections API.
Answers:
Collections.sort() that sorts collection of elements or objects of any type is a generic method.
Q28. What is raw type in Java?
Answer:
Raw type refers to generic type without specifying any parametrized type. For example, List is a raw type while List is a parameterized type. Raw types are retained for the backward compatibility to support code developed in older Java versions.
Q29. Why do we need generics in java?
Answer:
Code that uses generics has many benefits over non-generic code:
1) Stronger type checks at compile time: A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.
2) Elimination of casts: If you use generics, then explicit type casting is not required.
3) Enabling programmers to implement generic algorithms: By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.
Q30. What is a generic function?
Answer:
Generic functions are true functions that can be passed as arguments, returned as values, used as the first argument to funcall and apply, and otherwise used in all the ways an ordinary function may be used.
Java Generics Interview Questions and Answers
Q31. What is the main objective of Generics ?
Answer:
To provide type-safety and
To resolve type-casting problems
Q32. How can we restrict Generics to a subclass of particular class?
Answer:
In MyGeneric, Type T is defined as part of class declaration. Any Java Type can be used a type for this class. If we would want to restrict the types allowed for a Generic Type, we can use a Generic Restrictions. Consider the example class below: In declaration of the class, we specified a constraint “T extends Number”. We can use the class MyListRestricted with any class extending (any sub class of) Number – Float, Integer, Double etc.
class MyListRestricted<T extends Number> {
private List<T> values;
void add(T value) {
values.add(value);
}
void remove(T value) {
values.remove(value);
}
T get(int index) {
return values.get(index);
}
}
MyListRestricted<Integer> restrictedListInteger = new MyListRestricted<Integer>();
restrictedListInteger.add(1);
restrictedListInteger.add(2);
Q33. What is the alternative to Generics for providing type-safety ?
Answers
Arrays, which stores same-type of Objects within its capacity
but they are fixed in size
Q34. What is need of introducing Generics, when Arrays already present in Java ?
- Prior to Java 1.5 version release, Collection aren’t type-safe
- So, we can turn towards Arrays for type-safety
- But they are fixed in size which doesn’t allows to grow when more number of elements need to be added and similarly shrinks when elements are removed from Arrays
- Key advantage: In addition to this, generics provide type-safety as well as removes overhead of explicit type-casting problem
Q35. Whether it is allowed to define generic method as static ?
Answer
Yes, it is allowed to define Generics method as static
Q36. Write definition for generic method ?
Answer:
Syntax:
<access-modifier> <Type-parameter> <return-type> <method-name>();
Example:
public <T extends Number> void method1();
Related Interview Questions
- Core Java Interview Questions
- JSF Interview Questions
- JSP Interview Questions
- JPA Interview Questions
- Spring Framework Interview Questions
- Spring Boot Interview Questions
- Core Java Multiple Choice Questions
- 60 Java MCQ Questions And Answers
- Aricent Java Interview Questions
- Accenture Java Interview Questions
- Advanced Java Interview Questions For 5 8 10 Years Experienced
- Core Java Interview Questions For Experienced
- GIT Interview Questions And Answers
- Network Security Interview Questions
- CheckPoint Interview Questions
- Page Object Model Interview Questions
- Apache Pig Interview Questions
- Python Interview Questions And Answers
- Peoplesoft Integration Broker Interview Questions
- PeopleSoft Application Engine Interview Questions