0

Getting this exception while running following program

Exception in thread "main" java.lang.NullPointerException
    at pojo.Bill.main(Bill.java:20)
Java Result: 1

Bill.java

public class Bill {
    public static void main(String s[]){
        Bill b=new Bill();
        b.getBillDetails().setBillNo(444);// line 20
        System.out.println("bill no "+ b.getBillDetails().getBillNo());
    }

    private BillAction billDetails;

    public BillAction getBillDetails() {
        return billDetails;
    }

    public void setBillDetails(BillAction billDetails) {
        this.billDetails = billDetails;
    }

In BillAction there is getter and setter of billNo How to resolve this.

xrcwrn
  • 5,339
  • 17
  • 68
  • 129
  • 1
    What do you think this `b.getBillDetails()` does or should do? And why do you think so? – Sotirios Delimanolis Apr 14 '14 at 05:35
  • `billDetails` in the `Bill` is not initialized. – Rahul Apr 14 '14 at 05:36
  • If the application expects an empty `BillAction ` whenever a new `Bill` is created, you need to initialize `BillAction` variable in `Bill`s constructor. You are getting NPE because variable `billDetails` is currently Null. – ring bearer Apr 14 '14 at 05:51

3 Answers3

3

You are no where initializing BillAction for Bill object. By default the instance variables are set to null. So calling a method on BillAction will result in NullPointerException.

You need to override the default constructor and make sure you initialize the BillAction attribute as well in that. Or simply initialize it as mentioned by Sanjay in his answer.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
2

billDetails not initialized. and you are calling method on it. so whenever you are calling method on "null" you get null pointer exception

so do this, private BillAction billDetails= new BillAction();

Sanjay Rabari
  • 2,091
  • 1
  • 17
  • 32
0

You have default constructor and you are not initializing billDetails. so You will get null when you call getBillDetails()

niiraj874u
  • 2,180
  • 1
  • 12
  • 19