---
title: "What are annotations in Java? How are they used?"  
description: "What are annotations in Java? How are they used?"  
author: "Anubhav Sharma"  
published: 2024-07-18  
updated: 2024-07-18  
canonical: https://www.mindstick.com/forum/160949/what-are-annotations-in-java-how-are-they-used  
category: "java"  
tags: ["java", "javac"]  
reading_time: 2 minutes  

---

# What are annotations in Java? How are they used?

What are [annotations](https://www.mindstick.com/articles/12141/annotations-in-java-target-and-retention) in [Java](https://www.mindstick.com/articles/12214/web-development-company-in-india-laid-on-the-foundation-of-concrete-java-programming)? How are they used?

## Replies

### Reply by Ravi Vishwakarma

Annotations in Java are a form of metadata that can be added to Java code (classes, methods, variables, etc.). They provide information to the compiler and can be used at runtime by the JVM or other tools for various purposes.

### Types of Annotations

**Standard Annotations:** Java provides several built-in annotations in the `java.lang` package.

- `@Override`: Indicates that a method is overriding a method in a superclass.
- `@Deprecated`: Marks a method or class as deprecated, meaning it should not be used.
- `@SuppressWarnings`: Tells the compiler to suppress specific warnings.

```java
public class MyClass {
    @Override
    public String toString() {
        return "MyClass";
    }

    @Deprecated
    public void oldMethod() {
        // Do something
    }

    @SuppressWarnings("unchecked")
    public void myMethod() {
        // Do something
    }
}
```

**Meta-Annotations:** Meta-annotations are annotations that apply to other annotations. Some of the meta-annotations are:

- `@Retention`: Specifies how long the annotation is retained (runtime, class file, source).
- `@Target`: Specifies the kinds of elements an annotation type applies to (methods, fields, classes).
- `@Documented`: Indicates that an annotation should be documented by Javadoc and similar tools.
- `@Inherited`: Indicates that an annotation type is automatically inherited.

## Example:

```java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
    String value();
}
```


---

Original Source: https://www.mindstick.com/forum/160949/what-are-annotations-in-java-how-are-they-used

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
