What are Annotations in Java

πŸ’‘ Concept: Annotations

Annotations are metadata that provide additional information about Java code. They do not directly affect program logic but can be processed by the compiler or runtime to influence behavior.

πŸ“˜ Quick Intro

Java annotations are used to provide supplementary information about code elements like classes, methods, or fields. They are prefixed with @ and can be processed at compile-time or runtime.

🧠 Analogy

Think of annotations like labels on items in a warehouse. The label doesn’t change the item itself but provides extra information (e.g., "Handle with care").

πŸ”§ Technical Explanation

  • Annotations are declared with the @interface keyword.
  • Common built-in annotations include @Override, @Deprecated, @SuppressWarnings.
  • Custom annotations can be created to add context or behavior to your code.
  • Annotations can be processed by tools (e.g., compilers or frameworks like Spring).

🎯 Use Cases

  • βœ… Code documentation
  • βœ… Runtime configuration (e.g., Spring annotations)
  • βœ… Compile-time validation
  • βœ… JUnit test configuration

πŸ’» Example: Custom Annotation


import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Test {
    String value() default "Test method";
}

public class TestExample {
    @Test(value="Custom Test Method")
    public void myTestMethod() {
        System.out.println("Running test...");
    }

    public static void main(String[] args) {
        try {
            TestExample test = new TestExample();
            for (java.lang.reflect.Method method : test.getClass().getDeclaredMethods()) {
                if (method.isAnnotationPresent(Test.class)) {
                    System.out.println("Annotation found: " + method.getAnnotation(Test.class).value());
                    method.invoke(test);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

❓ Interview Q&A

Q1: What are annotations in Java?
A: Annotations are metadata that provide additional information about code elements.

Q2: Can annotations affect the program's behavior?
A: No, they provide metadata and are processed by tools like compilers or frameworks to alter behavior.

Q3: What is the syntax for creating an annotation?
A: Use @interface followed by the annotation name.

Q4: What is the purpose of the @Override annotation?
A: It indicates that a method is overriding a method from its superclass.

Q5: How do you define a custom annotation?
A: By using @interface and optionally specifying target elements and retention policy.

Q6: What does @Retention specify?
A: It defines how long the annotation should be retained (e.g., source, class, runtime).

Q7: What does @Target specify?
A: It defines where the annotation can be applied (e.g., method, field, class).

Q8: Can annotations be inherited?
A: Yes, if the @Inherited annotation is used.

Q9: What are some built-in annotations in Java?
A: @Override, @Deprecated, @SuppressWarnings.

Q10: How are annotations processed in Java?
A: Annotations can be processed at compile-time or runtime using reflection or annotation processors.

πŸ“ MCQs

Q1. What is an annotation in Java?

  • A type of variable
  • Metadata that provides additional information about code elements
  • A Java keyword
  • A way to define classes

Q2. Which built-in annotation indicates a method is overriding a superclass method?

  • @Override
  • @SuppressWarnings
  • @Deprecated
  • @Test

Q3. What does @Retention specify?

  • Where to apply the annotation
  • How long an annotation is retained
  • What the annotation does
  • None of the above

Q4. What is the syntax to create a custom annotation?

  • class
  • interface
  • @interface
  • annotation

Q5. Can annotations affect the program’s behavior?

  • Yes, always
  • No, they provide metadata
  • Sometimes
  • Only with specific annotations

Q6. What is the purpose of @Target?

  • Specifies annotation behavior
  • Specifies where an annotation can be applied
  • Defines annotation class
  • Marks deprecated methods

Q7. Which annotation marks a method as deprecated?

  • @Override
  • @Deprecated
  • @Test
  • @SuppressWarnings

Q8. How do you define a custom annotation?

  • By using @interface
  • By using class
  • By using enum
  • By using annotation

Q9. Which built-in annotation helps in suppressing compiler warnings?

  • @Override
  • @Deprecated
  • @SuppressWarnings
  • @Test

Q10. How do annotations affect testing?

  • By influencing code execution
  • Annotations are not used in testing
  • Annotations like @Test are used in frameworks like JUnit
  • By suppressing errors

πŸ’‘ Bonus Insight

Annotations are widely used in frameworks like Spring, Hibernate, and JUnit to define configuration, behavior, and testing rules declaratively.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

πŸ” Navigation

Learn More About Java β˜•

What is Java and its key features πŸ‘‰ Explained
Explain the Java Virtual Machine (JVM) πŸ‘‰ Explained
Difference between JDK, JRE, and JVM πŸ‘‰ Explained
What are Java’s main data types πŸ‘‰ Explained
Explain the concept of Object-Oriented Programming in Java πŸ‘‰ Explained
What is the difference between a class and an object πŸ‘‰ Explained
Explain encapsulation with an example πŸ‘‰ Explained
What is inheritance in Java and its types πŸ‘‰ Explained
Define polymorphism in Java with examples πŸ‘‰ Explained
What is abstraction in Java πŸ‘‰ Explained
Difference between abstract class and interface in Java πŸ‘‰ Explained
Explain method overloading and method overriding in Java πŸ‘‰ Explained
What are constructors in Java πŸ‘‰ Explained
What is the use of the static keyword in Java πŸ‘‰ Explained
Explain the difference between final, finally, and finalize in Java πŸ‘‰ Explained
Share:

Tags:


Feedback Modal Popup