i'm still starting to Learn OOP and there is this error that keeps popping out in my code; says that Exception in thread "main" java.lang.NullPointerException
public class SlumbookDriver{
public static void main(String args[]){
Slumbook[] contacts = new Slumbook[19];
... // index is an int and is the value of the index of the array
... // i feed it to a function "void viewEntry" that just shows
// the other attributes of the class Slumbook
viewEntry(index, contacts);
}
}
then i have the function viewEntry
public static void viewEntry(int index, Slumbook[] contacts){
Scanner sc = new Scanner(System.in);
if(index == 0){
System.out.println("Array is empty");
}
else{
String id = contacts[index].getIdNo();
System.out.println("Please enter ID number");
String idNo = sc.next();
if(id != idNo){
while(id != idNo && index != -1){
index--;
id = contacts[index].getIdNo();
}
if(index == -1){
System.out.println("ID does not exist");
return; //terminate action since the ID number does not exist
}
}
System.out.println(contacts[index].viewDetails());
}
}
You are just initializing the array
Slumbook[] contacts = new Slumbook[19];
but not its elements hence you will get a NullPointerException when you access the array element in statements like this:
String id = contacts[index].getIdNo();
When you create an array of objects, the objects within the array are not initialized, you need to initialize them using new operator before using them. Something like this:
contacts[index] = new Slumbook();
The problem here is that you have initialized an array of SlumBook, however the contents of the array need to be initialized.
For starters, just initialize the contents:
for (int i = 0; i < contacts.length; i++)
{
contacts[i] = new SlumBook();
}
Do this before using contacts in the method viewEntry(int, SlumBook[])
A NullPointerException happens when you try to access a field or a method in a reference but that reference is null.
For instance
Slumbook a = null;
a.getIdNo(); // NullPointerException
Same happens if you have an array
Slumbook [] data = new Slumbook[N];
data[i].getIdNo(); /// NPE
The second example would throw NPE if the reference contained at position i happens to be null.
When you get an exception a stack trace is shown and it contains the file name and exact line number(most of the times) where the exception occurred
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
I wrote a code for detecting cycle in graph.
The input is given such that there can be several lines with each line of form a # b .
It denotes that there is an edge from a to b.
My code worked and then I played with it a bit and came across a problem with line a and line c and with line b and line d.
When I combine line a and line c and write the declaration and instantiation together as "ArrayList[]" arr=new ArrayList[99999] , similarly line b and line d,then everything is working fine(Assuming I make appropriate changes like passing arr and visited as arguments between DFS and DFSvisit).
But If I write it as I have written below then I am getting Null pointer exception. What is the reason for this?
class Test {
ArrayList<Integer>[] arr; // line a
boolean[] visited; // line b
public static void main (String[] args) throws java.lang.Exception {
Test obj=new Test();
obj.DFS();
}
public void DFS() {
arr=new ArrayList[99999]; // line c
visited=new boolean[99999]; // line d
for(int i=0;i<99999;i++) {
arr[i]=new ArrayList<>(); //instantiate each element of "array of Arraylists"
}
boolean[] flag=new boolean[99999]; //a flag array to identify which elements of array are valid elements
Scanner sc=new Scanner(System.in);
while(sc.hasNext()) {
int a=sc.nextInt(); //take first number
sc.next(); //throw away "#" token
int b=sc.nextInt(); //take second number
flag[a]=true; //means arr[a] is valid
arr[a].add(b); //add b to adjaceny list of arr[a]
}
Test obj=new Test();
for(int i=0;i<99999 ;i++) {
if (flag[i]) { //call DFSvisit only if arr[i] is valid
obj.DFSvisit(i);
}
}
System.out.println("Cycle does not exist");
}
void DFSvisit(int i) { // basic DFS implementation
visited[i] = true;
for (int j=0;j<arr[i].size();) {
if (visited[arr[i].get(j)]==true) {
System.out.println("Cycle exists");
System.exit(0);
} else {
DFSvisit(arr[i].get(j));
}
j++;
}
visited[i] = false;
}
}
Error:
Exception in thread "main" java.lang.NullPointerException
at test.Test.DFSvisit(Test.java:59)
at test.Test.DFS(Test.java:49)
at test.Test.main(Test.java:18)
P.S. I know that If I try to use reference variable before it is initialised then I will get Null Pointer Exception. But here I am not able to see anywhere where that is happening. I have declared arr and visited as a member of class(outside every method). I am then initialising them after moving from main method to DFS method. In between I haven't tried to use either arr or visited but I am getting NPE anyway. Why is that?
You just got confused between two objects.
class Test {
ArrayList<Integer>[] arr;
boolean[] visited;
public static void main (String[] args) throws java.lang.Exception {
Test obj=new Test(); // here you create the first object. arr is null here
obj.DFS();
}
public void DFS() {
arr=new ArrayList[99999];
visited=new boolean[99999]; // here you initialize the fields of the first instance of the object
...
Test obj=new Test(); // here you create the second instance of the object. arr is null
for(int i=0;i<99999 ;i++) {
if (flag[i]) {
obj.DFSvisit(i); // here you call the method of the second object where arr is null. NPE
}
}
If you combine the lines, then the field initialization will happen during the object construction. That's why no NPE there.
This is hw and I am really stuck on how to get my code to return what I want it to return. I am trying to return a String value with a given index value. I thought all I had to do was return the string value at the given index but I am not getting the right answer.
public void add(String candidate){
if (candidate.equals(null)){
throw new RuntimeException();
}
String[] contenders = new String[candidates.length+1];
// copy the array manually because I'm restricted from ArrayLists
for (int i = 0; i < candidates.length; i++){
contenders[i] = this.candidates[i];
}
this.candidate = candidate;
contenders[contenders.length-1] = this.candidate;
this.candidates = new String [contenders.length];
After adding values to a newly constructed array the tester wants to get the string value at a given index
public String get(int index){
if (index < 0 || index > candidates.length) {
throw new RuntimeException("Your argument was not within bounds.");
}
for (int i = index; i < candidate.length(); i++){
candidate = candidates[index];
}
return candidate;
I have been working on it and I finally was able to have candidate stop pointing to null it is giving the wrong value for the given index so for example I want 'X' at candidate[3] but I am getting 'Y' because that is the last value that candidate keeps. I have tried just returning candidates[index] but then it tells me that the value at that index is null. As I have gone through the debugger it appears that my original array is not being copied over properly but I am not sure what I should try next. Thanks in advance.
This is my constructor:
public CandidateList(){
candidates = new String[0];
}
public CandidateList(String[] candidates){
this.candidates = new String[candidates.length];
CandidateList candidateList = new CandidateList();
There is a lot that can be improved in your code, let me add some comments
public void add(String candidate){
//if candidate is actually null you are calling null.equals
//which means this will always result in a NullPointerException
//you can remove this if if you want
if (candidate.equals(null)){
throw new RuntimeException();
}
...
//think about what you are doing here,
//you are setting this.candidates to a new empty array
//(is big contenders.length, but still empty)
this.candidates = new String [contenders.length];
Second part:
public String get(int index){
//you are missing an '=' in index >= candidates.length
if (index < 0 || index > candidates.length) {
throw new RuntimeException("Your argument was not within bounds.");
}
//this for loop is wrong, you are changing 'i' but never use it..
//just return candidates[index] like you said before.
//It was probably null because of the error above
for (int i = index; i < candidate.length(); i++){
candidate = candidates[index];
}
return candidate;
A note on the RuntimeException(RE): if you catch a NullPointerException (NPE) and throw a RE you are actually losing information (since NPE is a more specific error rather than RE). If you want to catch/throw put at least a significant message like "candidate cannot be null"
Let's now analyze the constructor:
public CandidateList(){
candidates = new String[0];
}
public CandidateList(String[] candidates){
// you are doing the same error as above here:
// when you do this you create an EMPTY list of size candidates.lenght
// correct code is this.candidates = candidates
this.candidates = new String[candidates.length];
// this is not necessary, constructors don't need to return anything,
//here you are just creating a new instance that will not be used anywhere
CandidateList candidateList = new CandidateList();
Constructors create objects, they don't return data. I suggest you to take a look at this question Does a Java constructor return the Object reference? and in general read a bit more about constructors
I am writing a basic program that iterates through an array of objects. I am then making a for-each loop and setting the values of each object in the array from user input. However, I am getting a null-pointer exception on the object I am using to store the value of the object array.
Here is my code:
import javax.swing.*;
public class Calculation {
public static Stations[] createStationArray(){
int numOfStations;
String string = JOptionPane.showInputDialog(null,"How many stations are there?");
numOfStations = Integer.parseInt(string);
Stations[] stations = new Stations[numOfStations];
JOptionPane.showMessageDialog(null, stations.length);
return stations;
}
public static void main(String[] args){
Stations[] stations;
stations = createStationArray();
System.out.println("stations array value" + stations);
for(Stations station : stations)
{System.out.println("station variable value" + station);
int stationNum = 1;
double amountOfWaste;
station.setStationNum(stationNum);
String string = JOptionPane.showInputDialog(null,"What is this Station's waste amount?");
amountOfWaste = Double.parseDouble(string);
station.setWaste(amountOfWaste);
System.out.println("Station " + station.getStationNum() + " has a waste amount of " + station.getWaste());
}
}
}
I am having issues in the for-each loop with the variable "station".
It is supposed to be the current object in the array list. However, I am getting a null-pointer exception. Here is the console output.
stations array value[LStations;#28787c16
Exception in thread "main" java.lang.NullPointerException
at Calculation.main(Calculation.java:27)
station variable value null
erException
at Calculation.main(Calculation.java:27)
You created an array of stations, but did not populate it. So when you loop over the array, every entry is still null.
You need to instantiate the Stations before calling methods on it. Try adding this inside createStationArray() after instantiating the Stations array:
for (int i = 0; i < numOfStations; i++)
stations[i] = new Stations();
I'm having a problem with retrieving and casting ArrayList from session. I get the following error:
javax.servlet.ServletException: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
I stored the arrayList in the session:
List<UserApplication> userList = uaDAO.searchUser(eds);
if (!userList.isEmpty()) {
request.getSession().setAttribute("userList", userList);
action_forward = EDITSUCCESS;
and for casting the session object to ArrayList, did the following:
EditStudentForm edt = (EditStudentForm)form;
if ((session.getAttribute("userList")) instanceof List){
List <UserApplication> studtList = (ArrayList<UserApplication>)session.getAttribute("userList");
}
try {
uaDAO.editUser(edt,studtList);
action_forward = EDITSUCCESS;
}
I'm getting the error over here in the DAO class:
public void editUser(EditStudentForm edt,List studtList) throws Exception {
PreparedStatement pst = null;
StringBuilder sb = new StringBuilder();
int stCode =Integer.parseInt(studtList.get(1).toString()); GETTING ERROR HERE
if (edt.getTitle() != null && !edt.getTitle().equals(studtList.get(2).toString())) {
sb.append("title = '").append(edt.getTitle()).append("'");
}
.
.
You are explicitly asking for 2nd (studtList.get(1)) and 3rd (studtList.get(2)) item in the list but never really make sure this list is big enough. Moreover your code apparently doesn't even compile:
if ((session.getAttribute("userList")) instanceof List){
List <UserApplication> studtList = ///...
}
try {
uaDAO.editUser(edt,studtList);
studtList is unaccessible in try block, also parenthesis in if statement are unmatched.
Check your studtList value.
From the error it seems your studtList only contain one item and you're try to get the second item with this code :
int stCode =Integer.parseInt(studtList.get(1).toString());
Change your code like this :
public void editUser(EditStudentForm edt,List studtList) throws Exception {
PreparedStatement pst = null;
StringBuilder sb = new StringBuilder();
if(studtList.size() > 1)
int stCode =Integer.parseInt(studtList.get(1).toString()); GETTING ERROR HERE
if (studtList.size() > 2 && edt.getTitle() != null && !edt.getTitle().equals(studtList.get(2).toString())) {
sb.append("title = '").append(edt.getTitle()).append("'");
}
}
In studtList there are no two elements and size of list maybe 1 or 0 elements, you should check it before try to call studtList.get(1). In ArrayList indexing start from 0 and if you want get first element you should call studtList.get(0).
In this code:
EditStudentForm edt = (EditStudentForm)form;
if ((session.getAttribute("userList")) instanceof List){
List <UserApplication> studtList = (ArrayList<UserApplication>)session.getAttribute("userList");
}
try {
uaDAO.editUser(edt,studtList);
action_forward = EDITSUCCESS;
}
You create a new variable 'studtList' that is never used. It's scope is only the { } pair around that one line.
There has to be another variable by that same name, studtList, in the outer scope so the 'editUser()' call can work.
Additional Note
As the other folks have answered, it looks like you may be doing a .get(1) and expecting the first element of the array list. Maybe. Maybe not.
I don't understand why this is giving me a null pointer exception when I try to add a value to the a1[i] array.
public class Array {
String text;
int total = 0, count = 0;
Array[] a1 = new Array[100];
Scanner scan = new Scanner(System.in);
public void setData() {
int i=0;
System.out.println(a1.length);
do {
System.out.println("Enter some data: ");
text = scan.next();
if (text.equals("end"))break;
a1[i].text = text; //I get a null pointer exception here. Not sure why.
i++;
} while (true);
}
Everything initialized in the a1 array is null. You'd have to put a new instance of Array() in there before doing anything with the member methods.
What this translates to: Every time you want to do something with a1[i], you'd have to have a new instance of Array in there first.
Example:
for(int i = 0; i < n; i++) {
a1[i] = new Array();
}
Because there isn't an object stored at a1[i]. What you're essentially saying at that line is:
null.text = text
which will break every time
You are getting a null-pointer exception, because you have allocated the space for 100 array elements, but you still need to initialize them:
So before accessing a1[i].text you need to initialize it by calling a1[i] = new Array()
Also I am quite sure, that you actually wanted to create some other kind of object, not Array. Array the class you are currently writing, as I understand, so you probably want to have multiple Strings, e.g. String[].
I recommend to you to use a LinkedList instead.
Array[] a1 = new Array[100]; //here you just create an array of references to objects which are set to null
a1[i].text = text; //before this line you should assign to a1[i] a reference to Array object for example a1[i] = new Array();