Friday, September 19, 2014

Java Generics, Reflection and Annotation interview questions and answers

1. What are the benefits of using Generics?

Keyword:
Compile time type check
Elimination of casts
Easy to implement generic algorithms

Answer:
a. Stronger type checks at compile time. 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.

b. Elimination of casts. An example:
List list = new ArrayList();
list.add("abc");
String s = (String) list.get(0); // need cast

List<String> list = new ArrayList<String>();
list.add("abc");
String s = list.get(0);   // no cast

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

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

Answer:
No, it will cause a compile error.

Different instantiations of the same generic type for different concrete type arguments have no type relationship.
Example:
public void printList(List<Object> list){
    for(Object o : list)
        System.out.println(o);
}
List<String> strList =new ArrayList<String>();
strList.add("abc");
printList(strList); // compiler error!!

3. What is unchecked warning? How to eliminate it?

Keyword:
Compile warning, assign raw type to parameterized type.
Eliminate: use parameterized type,  @SuppressWarnings("unchecked”).

Answer:
Unchecked warning occurs when you assign a raw type to a parameterized type.
Example:
List<String> list = new ArrayList(); //compile warning
The term "unchecked" means that the compiler does not have enough type information to perform all type checks necessary to ensure type safety.

To eliminate the unchecked warning, fix it as follows:
List<String> list = new ArrayList<String>();

If you can’t eliminate a warning, you can suppress the warning by using annotation:
@SuppressWarnings("unchecked")

4. What is type erasure?

Answer:
Java generics is implemented using type erasure mechanism. To implement generics, the compiler applies type erasure to:
a. Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded, while makes the produced bytecode contain only ordinary classes, interfaces, and methods.
b. Insert type casts if necessary to preserve type safety.
c. Generate bridge methods to preserve polymorphism in extended generic types.

Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.

5. How to create an object of given class using reflection?

Answer:
First, load the class using Class.forName() method, then call newInstance() method to create instance.

Example:
try{
    Class userClass = Class.forName("com.abc.User");
    User user = userClass.newInstance();
}
catch(ClassNotFoundException e) { ... }
catch(InstantiationException e) { ... }
catch(IllegalAccessException e) { ... }

6. How to invoke a Java method using Reflection?

Answer:
The following example shows how to invoke a Java method using Reflection:

package com.iraylab.sample;
import java.lang.reflect.Method;
public class Hello {

    public void sayHello() {
        System.out.println("Hello");
    }
   
    public void sayHelloTo(String name) {
        System.out.println("Hello " + name);
    }
   
    public static void main(String[] args) {
        try{
            //Get Class and create instance
            Class clazz = Class.forName("com.iraylab.sample.Hello");
            Object hello = clazz.newInstance();
           
            //Create and invoke a method that has no parameter
            Method method1 = clazz.getDeclaredMethod("sayHello");
            method1.invoke(hello);
           
            //Greate and invoke a method that has parameters
            Method method2 = clazz.getDeclaredMethod("sayHelloTo", String.class);
            method2.invoke(hello, "Java");
        } catch(Exception e){
            //...
        }
    }
}

7. How to get annotations at runtime using reflection?

Answer:
Use the getAnnotation method of java.lang.Class to get annotations applied to a class.
Use the getAnnotation method of java.lang.reflect.Method to get annotations applied to a method.
Example:
Define an annotation:
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation { }

Apply it to a class:
@MyAnnotation
public class User { }

Get annotation via reflection:
User user = new User();
Class userClass =  user.getClass();
for (Annotation annotation : userClass.getDeclaredAnnotations()) {
    //...
}

8. Describe annotation @Deprecated, @Override and @SuppressWarnings.

Answer:
@Deprecated - this annotation indicates that the marked element is deprecated and should no longer be used. The compiler generates a warning whenever a program uses a method, class, or field with the @Deprecated annotation.

@Override - this annotation informs the compiler that the element is meant to override an element declared in a superclass. While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.

@SuppressWarnings - this annotation tells the compiler to suppress specific warnings that it would otherwise generate. For example, a deprecated method is used, the compiler usually generates a warning. By using this annotation, the warning will be suppressed.

More Java Generics, Reflection and Annotation interview questions and answers: Java Interview Notes

  • What is generic type and parameterized type?
  • What is bounded type parameter?
  • What is autoboxing and unboxing in Java?
  • What is Reflection in Java?
  • What is the difference between getMethods() and getDeclaredMethods() of Class?
  • What are the different types of annotation?
  • How to create a custom annotation?
  • ......

Java Interview Notes

300+ frequently asked Java interview questions with concise summaries and detailed answers. Topics include: Java & OOP, Strings & Collections, IO JVM & GC, Multithreading, Generics Reflection & Annotations, Design Patterns, Java EE, Spring, JPA & Hibernate.



JavaScript Interview Notes

100+ frequently asked JavaScript interview questions with concise summaries and detailed answers. Topics include: JavaScript Basics, DOM, BOM, Object-Oriented JavaScript, Function, Scope, Closure, JSON, XML, Ajax, jQuery. 
Download on the AppStore    Get it On Google Play

 SQL Interview Notes

100+ frequently asked SQL and Database interview questions with concise summaries and detailed answers.  
Topics include: SQL Basic Concepts, SQL DDL & DML, Advanced SQL, Database Design and Performance Tuning.  
Download on the AppStore    Get it On Google Play


No comments:

Post a Comment