null pointer exception code in java code example

Example 1: What’s null pointer exception?

First, null keyword it does not refers to any object at all. 
Null keyword means no object.
null pointer excep: there is no object at all.
So you can't get access to the instance of that object

Example 2: how to use a try catch for a null pointer exception in java

int n;//decalred as null
n = n + 1;//null pointer exception
/////////////////////////////////////
int n = 5;
n = n + 1;//no null pointer exception

Example 3: null pointer exception method

public class MainClass {

    public static void main(String[] args) {
        anotherTest();
        test();
    }
    public static void test() {
        System.out.println("Printed from the test method.");
    }
    public static void anotherTest() {
        System.out.println("Printed from the anotherTest method.");
    }
}

Tags:

Java Example