What is the @SuppressWarnings annotation in Java?
Overview
Java is a compiled language which means the Java compiler converts the high-level java code to byte code. After the compilation phase, the compiler can throw warning messages that are helpful to improve the code.
If we don’t want to fix them, we can use the @SuppressWarnings annotation suppress the warning messages.
The @SuppressWarnings annotation
This annotation is used to suppress warnings in the annotated element. The annotation also needs a list of types of compiler warnings to suppress. Below is the syntax to specify the list of warnings.
To specify a single warning:
@SuppressWarnings(<warning name>)
Example: @SuppressWarnings("unchecked")
To specify more than one warning:
@SuppressWarnings({<warning1>, <warning2>, <warning3>})
Example: @SuppressWarnings({"unchecked", "deprecation"})
Different compiler vendors can have different warning types. But the most common ones are deprecation and unchecked.
deprecation: This indicates the compiler to ignore warnings due to the usage of deprecated elements.unchecked: This indicates the compiler to ignore warnings due to the usage of raw types.
Example
import java.util.Arrays;import java.util.List;public class main {@SuppressWarnings({"unchecked", "deprecation"})public static void printList(List... strings) {for (List<String> string: strings) {System.out.println(strings);}}public static void main(String[] args) {// Main main = new Main();List<String> stringList = Arrays.asList("educative", "edpresso");printList(stringList);}}
Explanation
- Lines 1–2: We import relevant classes.
- Lines 6–11: We define a private method called
printListthat loops through thevarargparameterstringsand prints the value. The method is annotated with@SuppressWarningsto suppress warnings from the method. - Line 13: We create an instance of the
Mainclass. - Line 14: We define a list of strings.
- Line 15: We call the
printListmethod with the list of strings.