Pages

November 15, 2016

Java Annotations Interview Questions and Answers

What are Java Annotations?
Java Annotations were added to the java from JDK 5.They allow us to add metadata information into our source code, although they are not a part of the program itself.

An annotation always starts with the symbol @ followed by the annotation name. The symbol @ indicates to the compiler that this is an annotation.


Where we can use annotations?

Annotations can be applied to the classes, interfaces, methods and fields.

Built-in Annotations in Java
There are three built-in annotations available in Java (@Deprecated, @Override & @SuppressWarnings are included in java.lang) that can be used for giving certain instructions to the compiler.

@Override is a marker annotation type that is used for instructing compiler that the annotated method is overriding the method.  This annotation type guards the programmer against making a mistake when overriding a method. e.g while changing the method signature of parent class, you must change the signature in child classes (where this annotation is being used) otherwise compiler would throw compilation error. This is difficult to trace when you haven’t used this annotation.

@Deprecated is a marker annotation type that can be applied to a method or a type (class/interface) to indicate that the method or type is deprecated and should no longer be used. The compiler generates a warning whenever a program uses a method, class, or field that has already been marked with the @Deprecated annotation.

When an element is deprecated, it should also be documented using the Javadoc @deprecated tag, as shown in the following example. Make a note of case difference with @Deprecated and @deprecated. @deprecated is used for documentation purpose.

/**
 * @deprecated
 * Students are not allowed to roam freely that's why letsRoam() in Student class is marked as deprecated.
 */
@Deprecated
public void letsRoam(){
 //
}



@SuppressWarnings instructs compiler to ignore specific warnings. e.g

letsRoam() is marked as Deprecated, so whenever you try to use it compiler will generate a warning. You can use @SuppressWarnings annotation, it would suppress that deprecation warning.
@SuppressWarnings("deprecation")
    void callRoam() {
        studentRoam.letsRoam();
}


@SuppressWarnings can be applied to types, constructors, methods, fields, parameters, and local variables.

The following are valid parameters to @SuppressWarnings:
unchecked: Give more detail for unchecked conversion.
path: Warn about nonexistent path (classpath, sourcepath, etc) directories.
serial: Warn about missing serialVersionUID definitions on serializable classes.
finally: Warn about finally clauses that cannot complete normally.
fallthrough: Check switch blocks for fall-through cases.

e.g @SuppressWarnings (value={"unchecked", "serial"})

@FunctionalInterface annotation, introduced in Java SE 8, indicates that the type declaration is intended to be a functional interface, as defined by the Java Language Specification.

How can you create custom Annotations?
Annotations are created by using @interface, followed by annotation name. e.g

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Target(ElementType.METHOD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation{
    int studentAge() default 18;
    String studentName();
    String stuAddress();
    String stuStream() default "CSE";
    String[] books();
}

All the elements that have default values (in above example age and stream are set to default) set while creating annotations can be skipped while using annotation.
@MyCustomAnnotation(
    studentName="Micheal",
    stuAddress="Kempten, Germany",,
    books={"Struts", "Java"}
)
public class MyClass {
//
}


Meta annotations are annotations that are applied to annotations. Documented, Inherited, Retention, and Target are meta-annotation types and are part of the java.lang.annotation package.

@Documented
annotation indicates that elements using this annotation should be documented by JavaDoc.
@Inherited annotation signals that a custom annotation used in a class should be inherited by all of its sub classes. If the user queries the annotation type on a class declaration, and the class declaration has no annotation of this type, then the class's parent class will automatically be queried for the annotation type. This process will be repeated until an annotation of this type is found or the root class is reached.
@Target specifies where we can use the annotation.
  • ANNOTATION_TYPE- The annotated annotation type can be used to annotate annotation type declaration.
  • CONSTRUCTOR- The annotated annotation type can be used to annotate constructor declaration.
  • FIELD- The annotated annotation type can be used to annotate field declaration.
  • LOCAL_VARIABLE- The annotated annotation type can be used to annotate local variable declaration.
  • METHOD- The annotated annotation type can be used to annotate method declaration.
  • PACKAGE- The annotated annotation type can be used to annotate package declarations.
  • PARAMETER- The annotated annotation type can be used to annotate parameter declarations.
  • TYPE- The annotated annotation type can be used to annotate type declarations.
@Target(value={TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})

@Retention indicates how long annotations with the annotated type are to be retained. The value of @Retention can be one of the members of the java.lang.annotation.RetentionPolicy enum:
  • RetentionPolicy.RUNTIME: The annotation should be available at runtime, for inspection via java reflection.
  • RetentionPolicy.CLASS: The annotation would be in the .class file but it would not be available at runtime.
  • RetentionPolicy.SOURCE: The annotation would be available in the source code of the program, it would neither be in the .class file nor be available at the runtime.
What are the annotations used in Junit  with Junit4 ?
@Test annotation indicates that the public void method to which it is attached can be run as a test case.
@Before annotation indicates that this method must be executed before each test in the class, so as to execute some preconditions necessary for the test.
@BeforeClass annotation indicates that the static method to which is attached must be executed once and before all tests in the class.
@After annotation indicates that this method gets executed after execution of each test.
@AfterClass annotation can be used when a method needs to be executed after executing all the tests in a JUnit Test Case class so as to clean-up the set-up.
@Ignores annotation can be used when you want temporarily disable the execution of a specific test.

How to create a Junit to make sure that the tested method throws an exception?
Using annotation Test with the argument as expected exception.
@Test (expected = Exception.class)

How should we ignore or avoid executing set of tests?
We can remove @Test from the respective test so as to avoid its execution. Alternatively we can put @Ignore annotation on the Junit file if we want to ignore all tests in a particular file.

How can we test methods individually which are not visible or declared private?
We can either increase their visibility and mark them with annotation @VisibleForTesting or can use reflection to individually test those methods.

-K Himaanshu Shuklaa..
Also Check : Java 8 Blogs

No comments:

Post a Comment