Java 5: Annotations

  Java Features     Java 5     Java 7     Java 8  
Java 5 features
 Enhanced for Loop |   Varargs |   Static import |   Autoboxing and unboxing |   Enum types |   Generics |   Annotations |   By date 

Annotations are introduced in Java 5 to provide a mechanism that allows you to write info about your code directly in the code. You can use annotations  within packages, classes, methods, variables and parameters.

Annotations syntaxes and elements

The character @ is used as prefix of the annotation name. In that way you indicate the compiler that the element is annotation.


The annotation below is called “Override” and is annotating the method print(). This info will be taken care of by the compiler.
void print()

Built in annotations

Java language includes a set of default annotations.

  1. @Deprecated
    This annotation warns  that the annotated element should not be used. The compiler generates a warning message. This one applies to methods, classes and fields. By using this annotation you should explain the reason why the element is depricated with an alternative solution.
  2. @Documented
    Indicates that the annotated elements will be documented.
  3. @Inherited
    This annotation indicates that the annotation inherit automatically to all the subclasses of the annotated class. You can apply this one to class elements.
  4. @Override
    Indicates that the element overrides an element of the super class. It is not mandatory
  5. @Retention
    This annotation indicates storing the marked annotation.
  6. @SafeVarargs
    By using this annotation the future Java compiler versions produces an error at compilation time if there is a potentil unsafe operations.
  7. @Target
    This one restricts the application of the annotation. For example:
    -CONSTRUCTOR  can be applied to a constructor.
    -FIELD                    can be applied to a field or property
  8. @SuppressWarnings
    Indicates the compiler not warn for a specific reason. For example if you prefer not to recieve warnings of unused private methods. See the following example!

    void print()

    Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

     Subscribe to Sar Maroof's RSS feeds!
     Mail this page to a friend!
     Bookmark this page!

Leave a Reply