Default Values for Annotation Elements

This section provides a tutorial example on how to declare default values for annotation elements and how to use default values in annotation invocation statements.

When you declare an annotation type, you can provide default values for annotation elements. The default value is specified at the end of the element declaration and follows the keyword "default"

When you invoke an annotation type that has an element with a default value, you can take the default value by skipping this element in the argument list.

Here is a sample program that shows you how to declare and use annotation element default values.

 * Copyright (c) All Rights Reserved.
class DefaultValueAnnotation {

   // Annotation declaration
   @interface Header {
      String usage();    // Usage of the targeted construct
      int version();     // Version number of targeted construct
      String author() default "Unknown"; // Default value provided

   // Annotation invocation - All values provided
   @Header(usage="Entry point", version=1, author="Herong")
   public static void main(String[] arg) {
      printMsg("Hello world!");

   // Annotation invocation - Default value used
   @Header(usage="Display message", version=10)
   public static void printMsg(String msg) {

If you compile and run the program, you will get:

herong> java

Hello world!

Table of Contents

 About This Book

 JDK - Java Development Kit

 Execution Process, Entry Point, Input and Output

 Primitive Data Types and Literals

 Control Flow Statements

 Bits, Bytes, Bitwise and Shift Operations

 Managing Bit Strings in Byte Arrays

 Reference Data Types and Variables

 Enum Types and Enum Constants

 StringBuffer - The String Buffer Class

 System Properties and Runtime Object Methods

 Generic Classes and Parameterized Types

 Generic Methods and Type Inference

 Lambda Expressions and Method References

 Java Modules - Java Package Aggregation

 Execution Threads and Multi-Threading Java Programs

 ThreadGroup Class and "system" ThreadGroup Tree

 Synchronization Technique and Synchronized Code Blocks

 Deadlock Condition Example Programs

 Garbage Collection and the gc() Method

 Assert Statements and -ea" Option

Annotation Statements and Declarations

 What Is Annotation

 Use "interface" as Annotation

Default Values for Annotation Elements

 Single-Element Annotation Invocation

 No-Element (Marker) Annotation Invocation

 getAnnotations() Method - Annotation APIs

 Predefined Annotation Types

 Java Related Terminologies

 Archived Tutorials


 Full Version in PDF/EPUB