Java generics was first introduced into the Java programming language in J2SE 5.0. Generics extends the Java type capabilities by enabling a Java type or method to operate on objects of different types. Generics also provides compile time safety, by identifying invalid types and throwing errors at compile time.
Important keywords are provided at the end of the questions. Review them, make them a part of Java generics vocabulary, and talk about them confidently during your interview process.
Generics in Java programming language enable Java types, i.e. classes and interfaces, to be declared as parameters to classes, interfaces and methods. Generics provide a way to reuse the same code with different inputs, i.e different types. Code that uses generics has many advantages over code that is non-generic.
A generic type is a generic class or interface that is parameterized over types.
Declaration of generic types - A generic class is declared using the format 'class MyClass
Instantiation of generic types - You instantiate a generic class using the new keyword as usual, but pass actual types within the parameter section. Example - 'MyClass
Generic methods are methods that are declared with type parameters. Generic methods can be static, non-static or constructors.
Declaration of generic methods -
Instantiation of generic methods
Bounded type parameters enable you to restrict the types that you can use as arguments for a parameterized type. For example if a method acts only on numbers, then you can use bounded parameters to specify that the method accepts only instances of Number or its sub-classes.
Similar to regular classes and interfaces, you can create sub-types of generic classes or interfaces by extending or implementing from the generic classes or interfaces.
For example, in Java collections API, ArrayList implements List and List implements Collections. The sub-type relation is preserved as long as the type argument does not vary. So, ArrayList implements List and List implements Collections.
Generics are applied at compile time provider stronger type checks. Once the type checks are complete, the compiler erases the type check code so that generics do not incur runtime over head...
*** See complete answer in the Java Interview Guide.
No Java generics cannot be applied to primitive types....
*** See complete answer in the Java Interview Guide.
No you cannot create instances of generic type parameters...
*** See complete answer in the Java Interview Guide.
The question mark (?) is termed as wildcard in generics code...
*** See complete answer in the Java Interview Guide.