0

Here is the exact error message:

Exception in thread "main" java.lang.NullPointerException
    at Application.main(Application.java:22)

I've tried to fix it with what I know... what am I doing wrong?

My code:

public class Application {

private String guitarMaker; 

public void setMaker(String maker) {

    guitarMaker = maker;

}

public String getMaker() {

    return guitarMaker;

}

public static void main (String[] args) {

    Application[] guitarists;
    guitarists = new Application[1];

    guitarists[0].setMaker("Example maker");
    System.out.println("My guitar maker is " + guitarists[0].getMaker());

}

}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Nick
  • 61
  • 8

3 Answers3

0

new Application[1] creates an array of one element, and all elements in that array (in this case, "all the elements" is "that only element") are null by default. That means that guitarist[0] is null, and calling setMaker on it will result in the NullPointerException.

You need to instantiate a guitarist and set assign it to guitarist[0]:

guitarist[0] = new Application();
yshavit
  • 42,327
  • 7
  • 87
  • 124
0
    public class Application {

private String guitarMaker; 

public void setMaker(String maker) {

    guitarMaker = maker;

}

public String getMaker() {

    return guitarMaker;

}

public static void main (String[] args) {

    Application[] guitarists;
    guitarists = new Application[1];
    guitarists[0] = new Application(); //need to create a new object
    guitarists[0].setMaker("Example maker");
    System.out.println("My guitar maker is " + guitarists[0].getMaker());

}

}

You were calling a method on a null object. The new Application[1] just creates an array after that you need to make new objects in each index of the array

rush2sk8
  • 362
  • 6
  • 16
0

you have to initialise array with size and call new Application() instead of new Application[1] something like:

Application[] guitarists = new Application[1];
guitarists[0] = new Application();

guitarists[0].setMaker("Example maker");
System.out.println("My guitar maker is " + guitarists[0].getMaker());
almeynman
  • 7,088
  • 3
  • 23
  • 37