I’m working on a Java project where I’m using an ArrayList to store user data. However, I’m encountering a NullPointerException when I try to access an element. Here is the relevant code:
import java.util.ArrayList;
public class UserList {
private ArrayList users;
public UserList() {
// Intentionally left users uninitialized to demonstrate the problem
}
public void addUser(String user) {
users.add(user);
}
public String getUser(int index) {
return users.get(index);
}
public static void main(String[] args) {
UserList userList = new UserList();
userList.addUser("Ashini");
System.out.println(userList.getUser(0));
}
}
I expected to see “Ashini” printed, but I get a NullPointerException instead. I understand this might be due to users being null, but I’m not sure how to properly initialize it. How can I fix this issue?
Ashini Ayodhya is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.