Course Info

#Programming Fundamentals 1

This is an introductory Programming module and assumes no prior knowledge of programming.

In this module, we will introduce you to the Java programming language through the Processing Development Environment (PDE) and then IntelliJ.

First, we will work through non-complex problems that will introduce you to the basic constructs of programming languages i.e. Sequence, Selection and Loops. You will also learn to use variables, different data types, manipulate the data, logical operators and methods. This will be done using processing.org

Then, using IntelliJ, we will progress to more complex problems that will briefly introduce you to object-oriented programming and data structures. You will do a deeper dive into both of these areas in the semester 2 module, Programming Fundamentals 2.

Null Pointer Exception

We are going to crash the program with a NullPointerException

In Driver, we should have the following code:

public class Driver {  
  
    Spot spot;  
    Scanner input = new Scanner(System.in);  
  
    public static void main(String args[]) {  
        System.out.println("Spot Console V1.0");  
        new Driver();  
    } 
     
    Driver() {  
        spot = new Spot();  
        drawSpot();  
    }  
    
    private void drawSpot() {  
        System.out.println("xCoord is : " + spot.xCoord);  
        System.out.println("yCoord is : " + spot.yCoord);  
        System.out.println("Diameter is : " + spot.diameter);  
	    }
    }

Remove this line of code from the Driver constructor:

    spot = new Spot();

You can simple comment it out for the moment like this:

//    spot = new Spot();

and run your program again.

NullPointerException

Your program should crash with the following error:

This is a NullPointerException which means that you haven’t called the constructor for an object (i.e. spot) before you started calling methods in the class (i.e. spot.getXCoord()). Notice in the output above the second line in the error is telling you that there was an error in Driver.java at line 19:

	Driver.drawSpot(Driver.java:19)

This is the exact line of code that crashed the program.

Also, note that the exit code of the program is no longer zero, it is 1, indicating that the program didn’t end ‘gracefully’.

Replace the line of code

Now change the line of code back to it’s original state:

    spot = new Spot();

and run the program again to make sure it is no longer crashing.