Amazing technological breakthrough possible @S-Logix pro@slogix.in

Office Address

  • #5, First Floor, 4th Street Dr. Subbarayan Nagar Kodambakkam, Chennai-600 024 Landmark : Samiyar Madam
  • pro@slogix.in
  • +91- 81240 01111

Social List

How to handle NullPointerException in java?

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.

Sample Code
  • 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);

}

}

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


Handle NullPointerException in java
Exception Handled Code