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:

Dr. Barry Burd holds an M.S. in Computer Science from Rutgers University and a Ph.D. in Mathematics from the University of Illinois. Barry is also the author of Beginning Programming with Java For Dummies, Java for Android For Dummies, and Flutter For Dummies.

This article can be found in the category: