0

I just saw this tutorial creating multiple objects using the same instance by applying the DAO pattern and tried it in a simple console, but I always get this message java.lang.NullPointerException I'm now confused, as far as I know, a constructor can be used once only, and the object will be immutable. Kindly look at this:

Fighter.java

public class Fighter {
    private String style;

    public Fighter() {}

    public String getStyle() {
        return style;
    }
    public void setStyle(String style) {
        this.style = style;
    }
}

FightersDAO.java

public class FightersDAO {
    public List<Fighter> getFighters(){

        List <Fighter> fighter = new ArrayList<>();
        String [] styles= { "Karate", "Sumo", "Pro-Wrestling" };

        for(int i=0; i < styles.length; i++) {
            Fighter temp = new Fighter();;
            temp.setStyle(styles[i]);
            fighter.add(temp);
        }
        return fighter;
    }
}

Demo.java

public class Demo {
    private static FightersDAO fighterDAO;
    public static void main (String [] args) {
        List <Fighter> fighters = fighterDAO.getFighters();

        for(Fighter e: fighters) {
            System.out.println(e.getStyle()); //this should output the objects, but nothing shows
        }
    }
}

Why is it null? What part did went wrong

0

3 Answers 3

3

The variable fighterDAO is never initialized. Therefore you get a NPE here:

List <Fighter> fighters = fighterDAO.getFighters();

To fix that use:

private static FightersDAO fighterDAO = new FightersDAO();
Sign up to request clarification or add additional context in comments.

1 Comment

Great! Thank you very much
3

private static FightersDAO fighterDAO;
I think there is a problem because it is not initialized.

Change it:
private static FightersDAO fighterDAO = new FightersDAO();

Comments

0

In your code
private static FightersDAO fighterDAO;// here is not initialized. its just a declaration so fighterDAO = null;

while executing below code will throw exeption List fighters = fighterDAO.getFighters();// means null.getFighters();

Below is the correct code

package aks;

import java.util.List;

public class Demo { private static FightersDAO fighterDAO= new FightersDAO();

public static void main (String [] args) {
    List <Fighter> fighters = fighterDAO.getFighters();

    for(Fighter e: fighters) {
        System.out.println(e.getStyle()); 
    }
}

}

You can analyse this by just debuggin on eclise or any IDE

If you want same instance use below code

private static FightersDAO fighterDAO = new FightersDAO();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.