Search code examples
javaobjectforeachnullpointerexceptionassign

Can someone explain why the assigned object inside forEach loop becomes null when it exits the forEach loop?


When i assign a object to an existing object in the foreach loop it is present, but when it exits the loop it suddenly becomes null and throws an nullpointerexception

Project project = new Project();
for (Project prjct: pps.getProjects()) {

    if (prjct.getCode().equals(projectCode)) {
       project = prjct;

       System.out.println("First occurrence : " + project.toString()); //The object is present here

    } else if (!prjct.getCode().equals(projectCode)) {
       project = null;
    }

    System.out.println("Second occurrence : " + project.toString()); //Object is also present here
}
System.out.println("Third occurrence : " + project.toString()); //Throws NullPointerException

Solution

  • You are updating project on every pass of the loop.

    It doesn't "suddenly become null" when you exit the loop; you are setting it to null on the last pass of the loop.

    else if (!prjct.getCode().equals(projectCode)) {
        project = null;
    }
    

    Without running your program, it is still obvious that prjct.getCode() does not equal projectCode, because you are entering the else if block and setting project = null.