Generics Interview Questions:-


  1. What are Generics?

Generics are used to create Generic Classes and Generic methods which can work with different Types(Classes).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 ?

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


  3. What are the restrictions in using generic type that is declared in a class declaration?

If a generic is declared as part of class declaration, it can be used any where a type can be used in a class method (return type or argument), member variable etc. For Example:- See how T is used as a parameter and return type in the class MyListGeneric.


  4. What is Bounded and Unbounded wildcards in Generics?

In generics '?' is known as wildcard and it represents an unknown type.

Types of Wildcard :-

1. Unbounded Wildcard.

2. Bounded Wildcard.

     (a). Upper bounded Wildcard.

     (b). Lower bounded Wildcard.

1. Unbounded Wildcard :- is used for list of unknown types using '?'(Type is not bounded).

2. Bounded Wildcard :- is used for unknown bounded types using '?' with extends or super keyword.

(a). Upper bounded Wildcard :- is used to restrict the unknown type to be a specific type or a subtype of that type using '?' with extends keyword.

(b). Lower bounded Wildcard :-is used to restrict the unknown type to be a specific type or a super type of that type using '?' with super keyword.


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

Use extends if you need to read from the collection (i.e.List<? extends T>). This will ensure that the collection itself contains items which extends A. This is read-only because there is no way to determine the exact type to add to the collection (the parameter could be List and there would be no way of ensure the type safety of an addition).

Use super if you want to write to the collection (i.e.List <? super T>). In this case, the collection can support addition of A types as we know the specified type of the collection is a super class of A. Therefore, A typed items can always be added to the collection.



  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 JUnit test.



  8. 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 Bloch suggested in Effective Java to prefer List over Array because List can provide compile time type-safety over Array.



  9. How can we restrict Generics to a super class of particular class?

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.



  10. What is Generic Methods?

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.

The syntax for a generic method includes a type parameter, inside angle brackets, and appears before the method's return type. For static generic methods, the type parameter section must appear before the method's return type.



  11. What is Generics, Inheritance, and Subtypes?

As you already know, it is possible to assign an object of one type to an object of another type provided that the types are compatible. For example, you can assign an Integer to an Object, since Object is one of Integer's supertypes:

Object someObject = new Object();
Integer someInteger = new Integer(10);

In object-oriented terminology, this is called an "is a" relationship. Since an Integer is a kind of Object, the assignment is allowed. But Integer is also a kind of Number, so the following code is valid as well:

public void someMethod(Number n) { /* . */ }

The same is also true with generics. You can perform a generic type invocation, passing Number as its type argument, and any subsequent invocation of add will be allowed if the argument is compatible with Number:



  12. What is Wildcards and Subtyping?

As described in Generics, Inheritance, and Subtypes, generic classes or interfaces are not related merely because there is a relationship between their types. However, you can use wildcards to create a relationship between generic classes or interfaces.

class A { /* . */ }
class B extends A { /* . */ }

It would be reasonable to write the following code:

B b = new B();
A a = b;

This example shows that inheritance of regular classes follows this rule of subtyping: class B is a subtype of class A if B extends A. This rule does not apply to generic types.



  13. What is Generic Types?

A generic type is a generic class or interface that is parameterized over types. The following Box class will be modified to demonstrate the concept.

A Simple Box Class

Begin by examining a non-generic Box class that operates on objects of any type. It needs only to provide two methods: set, which adds an object to the box, and get, which retrieves it:

public class Box {
private Object object;
public void set(Object object) { this.object = object; }
public Object get() { return object; }

Since its methods accept or return an Object, you are free to pass in whatever you want, provided that it is not one of the primitive types. There is no way to verify, at compile time, how the class is used. One part of the code may place an Integer in the box and expect to get Integers out of it, while another part of the code may mistakenly pass in a String, resulting in a runtime error.

A Generic Version of the Box Class

A generic class is defined with the following format:

class name(<>) T1, T2, ., Tn{ /* . */ }

The type parameter section, delimited by angle brackets (<>), follows the class name. It specifies the type parameters (also called type variables) T1, T2, ., and Tn.



  14. What is Upper Bounded Wildcards?

You can use an upper bounded wildcard to relax the restrictions on a variable. For example, say you want to write a method that works on List(Integer), List(Double), and List(Number); you can achieve this by using an upper bounded wildcard.

To declare an upper-bounded wildcard, use the wildcard character ('?'), followed by the extends keyword, followed by its upper bound. Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).



  15. Why do we need generics in java?

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.



  16. Explain Generics constructor in java.

A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic.

A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor.

The form of the formal type parameter list is identical to a type parameter list of a generic class or interface. The interface constructor is generic.



  17. What is Wildcard?

In generics '?' is known as wildcard and it represents an unknown type.

Types of wildcard:

1. Unbounded wildcard.

2. Bounded wildcard.

a. Upper bounded wildcard.

b. Lower bounded wildcard.

1. Unbounded wildcard: is used for list of unknown types using '?'(Type is not bounded).

2. Bounded wildcard: is used for unknown bounded types using '?' with extends or super keyword.

a. Upper bounded wildcard: is used to restrict the unknown type to be a specific type or a subtype of that type using '?' with extends keyword.

b. Lower bounded wildcard: is used to restrict the unknown type to be a specific type or a super type of that type using '?' with super keyword.


PHP

PHP is a server-side scripting language designed primarily for web development but is also used as a general-purpose programming language..

Read more