Why do i get the exception here?

This is the constructor of my class . With the following code :

public tester {
    setTitle("tester");
    initComponents();
    jTextArea6.setEditable(false);
    jEditorPane1.setEditable(false);
}

Every thing is fine . But with this code ,

public tester() {
    setTitle("tester");
    jTextArea6.setEditable(false);
    jEditorPane1.setEditable(false);
    initComponents();

}

i get the following exceptions :

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at tester.tester.<init>(tester.java:31)
at tester.tester$35.run(tester.java:1389)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:660)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

Why this is so ?

Answer

Without seeing the rest of the code (the definition of initComponents in particular, plus the definition of the fields) it’s not possible to be 100% certain.

But it’s almost definitely the case that the initComponents() method sets the value of jTextArea6 and/or jEditorPane1. In the second example you’re trying to dereference these fields before they’re set; which means they’d have the default value of null, and so would cause the NullPointerException to be thrown when you try to invoke methods on them.

Obviously one fix is to leave things as they are, perhaps with a comment stating

// Note - this method call initialises the fields.  DO NOT REORDER!!!

But a better solution is to get the compiler to check these things for you. If the two fields don’t ever change (i.e. they’re set up once and for all within the constructor), then you can and arguably should declare them final. In addition to this being very clear to others that they don’t have to consider the possibility of these fields changing, it means that they won’t have default values assigned initially, and the compiler will not let you dereference them before they’ve been assigned.

Leave a Reply

Your email address will not be published. Required fields are marked *