Reputation: 147
For some reason, I am getting a NullPointerException upon checking a String length in an 'if' statement. I am probably doing it wrong, but I wouldn't really know. What the code I am trying to write basically just changes a button's label, but only if the String 'label1' is 0 characters long (or not set), so that it can only be changed once.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Class1 {
public static String label1;
public static String one = ("Hello");
public static String two = ("Goodbye");
public static void main(String args[]) {
JFrame frame = new JFrame();
JPanel pane = new JPanel();
JButton button = new JButton();
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
if(label1.length() == 0) {
label1 = one;
JButton button = (JButton) e.getSource();
button.setText(label1);
}
if(label1.length() < 0) {
label1 = two;
JButton button = (JButton) e.getSource();
button.setText(label1);
}
} catch(Exception ex) {
System.out.println("ERROR");
ex.printStackTrace();
}
}
});
frame.setSize(350, 350);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(pane);
pane.add(button);
}
}
Upvotes: 2
Views: 12369
Reputation: 31161
Always check for null
. For example:
if(label != null && label.length() > 0) {...}
Out of interest, when is (label1.length() < 0)
ever true?
Upvotes: 0
Reputation: 877
In your example, the String object "label1" is not initialized and NULL. This means, if you try to call a method on a non-existing object, the NullPointerException
must happen.
To check if there is an Object assigned, try if (label1 != null)
.
To assign a value, do label1 = "my String"
- this initializes the String object.
Upvotes: 0
Reputation: 10320
label1 is null because you didn't initialize it.
label1 = "";
should fix your problem (it will be non-null size 0)
Upvotes: 0
Reputation: 13556
Assign some string value to label
public static String label1 = new String("someString");
We get NullPointerException
when calling some method on an object reference which has not been assigned any object yet and the reference which is erferring to null
Upvotes: 0
Reputation: 121998
public static String label1;
to use the line if(label1.length() == 0) {
you have to intialize lable1
before
You are not intialised lable! anywhere any using it
Try to change that line
public static String label="";
or add extra null condition
if(label1 != null && label1.length() == 0) {
Upvotes: 8