Handling NullPointer Exception

Description

The code given here shows how to animate the text. NullPointer Exception is thrown due to the access of reference variable without creating object. Using reference variable after the proper object creation code solves the problem of NullPointer Exception.

  • Filename: AnimatingText.java

import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;

public class AnimatingText extends JFrame implements ActionListener{
JLabel label;
JLabel label2;
static AnimatingText frame;
public AnimatingText() {
label = new JLabel( "Welcome to learn Java! ");
getContentPane().add(label, BorderLayout.NORTH);
javax.swing.Timer timer = new javax.swing.Timer(100, this);
timer.start();
}
public void actionPerformed(ActionEvent e) {

String oldText = label.getText();
String s1= oldText.substring(1);
String s2= oldText.substring(0, 1);
String newText = s1 + s2;
label.setText( newText );
}
public static void main(String[] args) {

frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.setSize(300,100);
frame.setVisible(true);

}

}

  • Exception Handled Code:

import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;

public class AnimatingText extends JFrame implements ActionListener{
JLabel label;
JLabel label2;
static AnimatingText frame;
public AnimatingText() {
label = new JLabel( "Welcome to learn Java! ");
getContentPane().add(label, BorderLayout.NORTH);
javax.swing.Timer timer = new javax.swing.Timer(100, this);
timer.start();
}
public void actionPerformed(ActionEvent e) {

String oldText = label.getText();
String s1= oldText.substring(1);
String s2= oldText.substring(0, 1);
String newText = s1 + s2;
label.setText( newText );
}
public static void main(String[] args) {
frame = new AnimatingText();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.setSize(300,100);
frame.setVisible(true);

}

}

Handling NullPointer Exception
  • Object for reference variable frame is not created. Hence NullPointerException is thrown here.
  • Exception Handled Code

Handling NullPointer Exception