Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What are annotations in Java and what are some commonly used built-in annotations? Java में annotations क्या हैं और commonly used built-in annotations क्या हैं?

Answer

Annotations are metadata attached to code (classes, methods, fields) that don't directly affect program logic but provide information used by the compiler, tools, or at runtime via reflection.

AnnotationPurpose
@OverrideVerifies a method actually overrides a parent method (compile-time check)
@DeprecatedMarks code as outdated, generates compiler warnings if used
@SuppressWarningsTells the compiler to ignore specific warnings
@FunctionalInterfaceEnforces an interface has exactly one abstract method
@SafeVarargsSuppresses unchecked warnings for varargs with generics
class Animal {
    public void makeSound() {
        System.out.println('Some sound');
    }
}

class Dog extends Animal {
    @Override  // catches typos - if method name doesn't match parent, compile error
    public void makeSound() {
        System.out.println('Bark');
    }
}

class Utility {
    @Deprecated
    public static void oldMethod() {
        System.out.println('This method is outdated');
    }

    @SuppressWarnings('unchecked')
    public static void suppressExample() {
        List rawList = new ArrayList();
        List<String> list = rawList;  // would normally warn, suppressed here
    }
}

// Using a deprecated method triggers a compiler warning
Utility.oldMethod();  // warning: [deprecation] oldMethod() is deprecated

// @Override catching a real bug
class BadDog extends Animal {
    // @Override
    // public void makeSond() {  // typo! Without @Override, this silently
    //     System.out.println('Bark');  // creates a NEW method instead of overriding
    // }
}

Annotations code (classes, methods, fields) से attached metadata हैं जो directly program logic को affect नहीं करते पर compiler, tools, या runtime पर reflection के ज़रिए इस्तेमाल होने वाली information देते हैं।

Annotationउद्देश्य
@OverrideMethod वाकई parent method override करता है, verify करता है
@DeprecatedOutdated code mark करता है
@SuppressWarningsSpecific warnings ignore करने को कहता है
@FunctionalInterfaceएक abstract method enforce करता है
class Animal {
    public void makeSound() {
        System.out.println('Some sound');
    }
}

class Dog extends Animal {
    @Override  // typos पकड़ता है
    public void makeSound() {
        System.out.println('Bark');
    }
}

class Utility {
    @Deprecated
    public static void oldMethod() {
        System.out.println('यह method outdated है');
    }

    @SuppressWarnings('unchecked')
    public static void suppressExample() {
        List rawList = new ArrayList();
        List<String> list = rawList;
    }
}

Utility.oldMethod();  // deprecation warning

Was this answer clear?