0

During my practice session, I got one simple question that what happens when I assign null to object and invoke some function? So I tried my self by handling main method with null pointer exception, it doesn't work. Is there anyway to call methods after assign null to object. I want to execute my methods.

public class MyProgram {

    public void test1()
    {
        System.out.println("say hello");
    }
    public void test2()
    {
        System.out.println("say hi");
    }

    public static void main(String[] args) throws NullPointerException{
        // TODO Auto-generated method stub
     MyProgram myPrg= new MyProgram();
     myPrg = null;
     myPrg.test1();
     myPrg.test2();
    }

}

If not possible, Please explain me the reason!!!

Vinod
  • 2,263
  • 9
  • 55
  • 104

5 Answers5

0

You call myPrg = null;

Calling methods on a null reference results in a NullPointerException.
Remove that line and it should work.

nhaarman
  • 98,571
  • 55
  • 246
  • 278
  • Yes I know. But I want to know how to handle the NullPointerException in that situation. – Vinod Apr 10 '14 at 19:16
  • There is nothing to call your methods on anymore. Just make sure your references aren't `null`. You could also surround it with a `try catch` statement, but for `NullPointerException`s, this is bad practice. – nhaarman Apr 10 '14 at 19:17
0

I usually check for null before calling a method, if there's a chance the variable could be null. So:

if (myPrg != null) {
  myPrg.test1();
  myPrg.test2();
} else {
  // do something else instead if needed
}

I typically use this first approach when I wouldn't need to do anything, or would need to do something completely different if the object were null.

Or set myPrg to something non-null if it's null, before calling the test methods:

if (myPrg == null) {
  myPrg = new MyProgram();
}
myPrg.test1();
myPrg.test2();

I typically use this second method for cases where the object may be null because it has not been initialized yet, and if that's the case, I want to initialize it, and then execute the code as usual.

Alternately, you can use try/catch:

try {
  myPrg.test1();
  muPrg.test2();
} catch(NullPointerException e) {
  // do something else instead
}

try/catch is not usually done for NullPointerException. It's better programming practice to use one of the other methods above.

by the way if you do any of these things, you can take out the throws NullPointerException clause, since there won't be anything to cause it to throw the exception anymore.

Note that you can't call a method on a null object. This is in part because a null object doesn't know what type it is (so it doesn't know it's a null object of type MyProgram) and also because typically the methods on a class require some context from the object, which is why they were written as methods on the class.

If you have methods that don't require an object to act on, make them static.

public static void test1() {
  System.out.println("say hello");
}

Can be called without needing an instance of MyProgram to call it on. You could just call MyProgram.test1();

I think that may be what you're looking for rather than a way to handle a NullPointerException

PurpleVermont
  • 1,179
  • 4
  • 18
  • 46
0

In order to handle the NullPointerException, you have to add a try/catch block around where the exception could be (and will be, in this case) thrown.

Take a look at this code:

public class MyProgram {

    public void test1()
    {
        System.out.println("say hello");
    }
    public void test2()
    {
        System.out.println("say hi");
    }

    public static void main(String[] args) {
     MyProgram myPrg= new MyProgram();
     myPrg = null;

     // use a try/catch block to catch the NullPointerException
     try {
         myPrg.test1();
         myPrg.test2();
     } catch (NullPointerException) {
        System.out.println("A NullPointerException was thrown!");
     }
}

Take note that I changed two things:

  1. I removed the throws NullPointerException from the main method - it is no longer needed because it is handled in the method itself
  2. I added a try/catch block from lines 18 - 23 to catch the exception if it is thrown (which it is)

In addition to simply catching the null reference, you could check for a null reference and then either perform the operation or not:

public class MyProgram {

    public void test1()
    {
        System.out.println("say hello");
    }
    public void test2()
    {
        System.out.println("say hi");
    }

    public static void main(String[] args) {
     MyProgram myPrg= new MyProgram();
     myPrg = null;

     // test if myPrg is null
     if (myPrg != null) {

        // proceed with tests
         myPrg.test1();
         myPrg.test2();
     } else {
        // print a message
        System.out.println("myPrg is null!");
     }
}

Here, we simply test if myPrg is null on line 17 and, if it is not null, proceed with the tests - otherwise print a message saying that myPrg is null.

I hope this helps!

joshreesjones
  • 1,934
  • 5
  • 24
  • 42
0

You can handle the exception, but It's impossible to call your methods. The reason is that you methods are connected to a object and without that object it's impossible to know what methods you are talking about. Even if the name makes a connection in your head there is no such connection for java.

If you don't need any object at all and you just want methods you can achieve this with static methods and without any variables. Something like

class MyProgram {

public static void method() {}

public static void main() { MyProgram.method(); }

}

In this case you are using the class to tell witch metod you want to call rather than a object.

Probably this is the wrong design for whatever you want to do, but I'm assuming you are looking to understand the reason rather than making something work.

monocell
  • 1,411
  • 10
  • 14
0

NullPointerException is RuntimeException therefore the try/catch is optional for it . practical its not a good practice to handle the RunTimeExceptions . I Would like to write it AS

if (myPrg != null) { myPrg.test1(); myPrg.test2(); }

To know more about the exceptions in JAVA http://johnpwood.net/2008/04/21/java-checked-exceptions-vs-runtime-exceptions/

mkiswani
  • 19
  • 2