Home

How to Use Java’s SuppressWarnings Annotation

|
Updated:  
2017-05-04 13:16:43
|
Java Essentials For Dummies
Explore Book
Buy On Amazon
The annotation is extra code that provides useful information about the nature of your Java program. The following codes uses the SuppressWarnings annotation.

import java.awt.FlowLayout;

import javax.swing.JFrame;

import javax.swing.JButton;

@SuppressWarnings("serial")

public class SimpleFrame extends JFrame {

public SimpleFrame() {

setTitle("Don't click the button!");

setLayout(new FlowLayout());

setDefaultCloseOperation(EXIT_ON_CLOSE);

add(new JButton("Panic"));

setSize(300, 100);

setVisible(true);

}

}

When you use a SuppressWarnings annotation, you tell Java not to remind you that your program contains certain questionable code. The line @SuppressWarnings("serial") tells Java not to remind you that you've omitted something called a serialVersionUID field. In other words, the SuppressWarnings annotation tells Java not to display a warning.

supresswarnings annotation in java Without a SuppressWarnings annotation, Java warns you about a missing serialVersionUID field.

“And what,” you ask, “is a serialVersionUID field?” It’s something having to do with extending the JFrame class — something that you don’t care about. Not having a serialVersionUID field generates a warning, not an error. So live dangerously! Just suppress the warning and don’t worry about serialVersionUID fields.

  • In JShell, type the following sequence of declarations and statements. What happens? Why?
jshell> import javax.swing.JFrame

jshell> JFrame frame

jshell> frame.setSize(100, 100)

jshell> frame = new JFrame()

jshell> frame.setSize(100, 100)

jshell> frame.setVisible(true)

Change the statement

setLayout(new FlowLayout());

  • to
setLayout(new BorderLayout());

What difference does this change make when you run the program?

About This Article

This article is from the book: 

About the book author: