2013-07-26

Exception in thread "main" java.lang.NullPointerException

This is probably the most common error a beginning programmer in Java would encounter. Especially when creating your own instance variables (which would have default values set, so compiler won't complain about uninitialized values). In the example below, the object variables f and b both have a default value of null set. The array myints is also default to null. When we try to access the null value, it would cause the NullPointerException and the program have crashed out.


MostCommonMistakeInJava.java
 1 package example;
 2 import javax.swing.*;
 3 
 4 public class MostCommonMistakeInJava {
 5 
 6     private static JFrame f;
 7     private static JButton b;
 8     private static int[] myints;
 9     
10     public static void main(String[] args) {
11         f = new JFrame();
12 
13         f.add(b); // will also crash here
14         myints[0] = 1; // will crash here
15                 
16     }
17 }





No comments:

Post a Comment

Github CoPilot Alternatives (VSCode extensions)

https://www.tabnine.com/blog/github-copilot-alternatives/