-1

I'm writing a for loop to iterate through the array and find the index of the employee with the social security number of 123456789. Why do I keep getting a NullPointerException?

.getSocSecNum() returns a String

empnew[21] = Empthe1;
String temp = "123456789"
for(int i = 0; i < empnew.length - 1; i++){
if(empnew[i].getSocSecNum().compareTo(temp) == 0){
System.out.println("the location of the employee is " + i);
        }
    }

I want it to output "the location of the employee is 21" but all I get is a NullPointerException

Alex
  • 7
  • 1
  • What have you tried so far? In particular, have you tried printing out the array or the various intermediate values to see if there is a `null` somewhere? (Or, if you don't understand what a `NullPointerException` is, take a look at [this question](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it)'s answers.) – jirassimok Oct 01 '19 at 21:29
  • Whenever I try to print out the array like this it just gives me a Nullpointer is it because my array is not completely filled??? – Alex Oct 01 '19 at 21:33
  • It seems likely that that is the case, yes. Try printing the array before the loop using [`java.util.Arrays.toString`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/Arrays.html#toString(java.lang.Object%5B%5D)) or [`deepToString`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/Arrays.html#deepToString(java.lang.Object%5B%5D)). – jirassimok Oct 01 '19 at 21:35

1 Answers1

0

The problem is most likely that empnew has at least one null in it.

So in the loop, you try to get empnew[i].getSocSecNum(), which expands to null.getSocSecNum(), which gives you a null pointer exception, because you can't access class members on null, because it isn't a real object.

The easiest solution might be to just check that empnew[i] != null before accessing the value:

if (empnew[i] != null && empnew[i].getSocSecNum...) {
    ...
}
jirassimok
  • 3,850
  • 2
  • 14
  • 23