Dominik
Dominik

Reputation: 4778

Java NullPointerException

I get a java.lang.NullPointerException in my Class Article in line 5.

In one class I create the object Article article = new Article(), then I call article.addPrice(quantity, price); with quantity being an Integer with the value '1' and price being a Float with the value '1.32'.

1: public class Article {
2:  private List prices;
3:  public void addPrice(Integer quantity, Float qtyPrice){
4:      Price price = new Price(quantity, qtyPrice);
5:      this.prices.add(price);
6:  }
7: }

Upvotes: 0

Views: 213

Answers (6)

Rishikesh Dhokare
Rishikesh Dhokare

Reputation: 3589

In your code, you have just declared the list prices and not initialized it.

Use following corrected code :

1:  public class Article {
2:  private List<Price> prices = new ArrayList<Price>();
3:  public void addPrice(Integer quantity, Float qtyPrice){
4:      Price price = new Price(quantity, qtyPrice);
5:      this.prices.add(price);
6:  }
7: }

so till the time you do new ArrayList(), you have null in prices and you are trying to invoke .add(price) on null in line 5, hence the NullPointerException.

Upvotes: 0

Mike M
Mike M

Reputation: 1778

public class Article
{
 private List<Price> prices = new ArrayList<Price>();

 public void addPrice( Integer quantity, Float qtyPrice )
 {
  Price price = new Price( quantity, qtyPrice );
  prices.add( price );
 }
}

Unless you vastly oversimplified the problem, I can't think of any reason the above would not work.

Upvotes: 2

Sam
Sam

Reputation: 2579

You have not initialized the private list variable. Insert this as the first lines in addPrice:

if (prices == null) {
    prices = new ArrayList<Price>();
}

This will ensure the prices list is initialized prior to being accessed.

Upvotes: 1

Peter Perh&#225;č
Peter Perh&#225;č

Reputation: 20792

you need to initialize the prices list.

prices = new ArrayList<Price>();

Upvotes: 7

btreat
btreat

Reputation: 1554

The 'prices' list is not initialized which causes the null reference.

Upvotes: 3

meriton
meriton

Reputation: 70584

Your code never assigns prices, therefore the field still contains its initial value, which is null.

In plain english, you program would read: Create a new price object and add it to the list I assigned to prices. You didn't assign a list, and therefore the computer can't know which list to add to ...

Upvotes: 5

Related Questions