Java @SuppressWarnings Annotation Example

www.la‮ttu‬uri.com
Java @SuppressWarnings Annotation Example

In Java, the @SuppressWarnings annotation is used to suppress specific warnings that are generated by the compiler. This can be useful when a piece of code generates a warning that is not relevant or when the code is correct despite the warning.

Here is an example of how the @SuppressWarnings annotation can be used:

import java.util.ArrayList;
import java.util.List;

public class MyClass {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("hello");
        list.add("world");

        for (Object element : list) {
            System.out.println(element);
        }
    }
}

In this example, the @SuppressWarnings("unchecked") annotation is used to suppress the unchecked warning that is generated when the list object is created. Without the @SuppressWarnings annotation, the compiler would generate a warning like this:

warning: [unchecked] unchecked conversion
  required: List<Object>
  found:    ArrayList
List list = new ArrayList();
                   ^

It is important to note that the @SuppressWarnings annotation should be used sparingly and only when it is necessary. It is usually better to fix the code that is causing the warning rather than suppressing the warning with the @SuppressWarnings annotation.

Created Time:2017-11-01 22:29:46  Author:lautturi