0

Hi Guys I am new to Java Why does it throws null pointer exception?? My Customer Class

    package com.syncfusion;

    import java.util.List;

    public class Customers {

        private List<String> customerNamesList;

        public void addCustomerName(String customerName) {

            customerNamesList.add(customerName);
            System.out.println(customerName);

        }


        public void printAllCustomers() {
            for(String customer : customerNamesList) {

                System.out.println(customer);


            }
        }
    }

and my Main function is as shown below:

package com.syncfusion;



public class Persons {



    public static void main(String[] args) {
         Customers customer = new Customers();
         customer.addCustomerName("Inteflex Inc");




    }
}

Why does it throw null pointer ? and I hope i have instanciated the Customer Class but it has error

2 Answers2

0

You have to initialize the customerNamesList this way:

private List<String> customerNamesList = new ArrayList<>();

Or using a constructor:

public class Customers {

    private List<String> customerNamesList;

    public Customers() {
        this.customerNamesList = new ArrayList<>();
    }

    // ...other methods
}
Giancarlo Romeo
  • 663
  • 1
  • 9
  • 24
0

Change the list initialization to below :

 private List<String> customerNamesList = new LinkedList<String>();

Why your code has NullPointerException ? Because you were using List directly which is interface (abstract type) you need to initialize with its implementation (ArrayList, LinkedList according to your list manipulation requirement)

Sagar Joon
  • 1,387
  • 14
  • 23