new to ArrayList and was wondering what I am doing wrong. I keep getting a null pointer exception when trying to addRecord...

import java.util.*;

public class StudentDB {

   private List<String> studentDB;


    public StudentDB(String db) {
	 
	     List<String> studentDB = new ArrayList <String>();
		  studentDB.add("");
	 }
	 
	 public void addRecord(String recordAdd) {
	 
	   studentDB.add(recordAdd);	  
	 }
}
public class TestStudentRec {

     public static void main (String[] args) {

          StudentDB db = new StudentDB("this");
	 db.addRecord("added record");
	 System.out.print(db);

	 }
}

Recommended Answers

All 3 Replies

Duplicate definitions of studentDB on lines 5 and 10.
By defining a new one on line 10 that's the one that gets initialised, but it ceases to exist at the end of the constructor method.

thanks for the help!

import java.util.*;

public class StudentDB {

   private List<String> studentDB;


    public StudentDB(String db) {

		   studentDB = new ArrayList <String>();
		   // studentDB.add("");
	 }
	 
	 public void addRecord(String recordAdd) {
	 
	   studentDB.add(recordAdd);	  
	 }
	 
	 public int getSize() {
	  
	  int i = studentDB.size();
	  return i;
	 }
	
	 public List<String> printArrayList() {
	 
	  return studentDB;
	 }
}

public class TestStudentRec() {

   public static void main (String[] args) {

	 StudentDB db = new StudentDB("this");
	 db.addRecord("added record");
	 db.addRecord("added another record");
	 
	 int i = db.getSize();
	 System.out.println(i);
	 
	 
	 List<String> ls = db.printArrayList();
	 System.out.println("arraylist: " + ls);
	 
   
	 }
}

out:
2
arraylist: [added record, added another record]

OKI, that's great.
Two small suggestions:
you can initialise studentDB at the same time as you declare it (line 5), as in
private List<String> studentDB = new ArrayList <String>();
which is a bit easier to follow that declaring it there and initialising it in the constructor.
You have a String parameter on the constructor, but you don't use it - this will generate a compiler warning if you have the right compiler settings. Best to not have it of you don't use it.
J
ps: mark thread as solved?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.