What is SuppressWarnings annotation? Along with Java program


What are Annotations in Java ?.

Annotations in Java are metadatas that adds information to your code in a formal way so that you can keep track to the information added at a later stage. They provide a Java programmer information which describes the program fully in a sophisticated way. Annotations help us in generating descriptor files and giving us way to write boilerplate code each time.

Annonations in Java have a symbol @ in its syntax declaration. Java contains general purpose built in annotations defined in java.lang package as :

@SuppressWarnings : Generally, it is used when we want compiler to turn off the warnings it is displaying.


Program to demonstrate @SuppressWarning annotation in Java

package com.hubberspot.example;

import java.util.Random;
import java.util.Scanner;
import java.util.Date;
import java.util.ArrayList;
import java.util.Set;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.AbstractCollection;
import java.util.Arrays;
import java.util.Vector;
import java.util.TreeSet;

//1. unused imports warning suppressed by 
//@SuppressWarnings("unused")

//2. The serializable class SuppressWarningDemo does 
//not declare a static final serialVersionUID field 
//of type long warning suppressed by 
//@SuppressWarnings("serial")

@SuppressWarnings({"unused", "serial"})
public class SuppressWarningDemo extends Exception {
 
//3. finally block does not complete normally
//warning suppressed by @SuppressWarnings("finally")

 @SuppressWarnings("finally")
 public static void main(String[] args) {

//4. The constructor Date(int, int, int) is deprecated
// warning suppressed by @SuppressWarnings("deprecation")  

  @SuppressWarnings("deprecation")
  Date date = new Date(2012,8,20);
  
//5. ArrayList is a raw type. References to generic type 
// ArrayList should be parameterized warning suppressed
// by @SuppressWarnings("rawtypes")  

  @SuppressWarnings("rawtypes")
  ArrayList list = new ArrayList();
  
  try{ 
   
  }finally{
   return;
  }
  
 }

}