Lachie Lachie - 1 year ago 337
Java Question

NullPointerException (Java)

I've tried looking at posts on this issue but am still having some trouble with this error in my code. So in the fourth line, I create an instance variable called

SongDatabase
to access the
SongDatabase
class. But when I get down to the line,
SongDatabase.addNewSong();
under
case 1
, I get a java.lang.NullPointerException: null error.

Interface class:

public class Interface
{
Scanner console = new Scanner(System.in);
private SongDatabase SongDatabase;

public static void main(String[] args) {
Interface intFace = new Interface();
intFace.run();
}

private void run() {
switch (userInput) {
case 1:
SongDatabase.addNewSong();
break;
case 2:
SongDatabase.removeSong();
break;
case 3:
SongDatabase.sortSongs();
break;
default:
System.out.println("Please enter a valid number.");
break;

}
}


SongDatabase class:

public class SongDatabase {
Scanner console = new Scanner(System.in);
private Song song1, song2, song3, song4;

public void addNewSong() {
if (song1 == null) {
song1 = getFromUser();
}
else if (song2 == null) {
song2 = getFromUser();
}
else if (song3 == null) {
song3 = getFromUser();
}
else if (song4 == null) {
song4 = getFromUser();
}
else {
System.out.println("The database is currently full. Please delete a song before adding a new one.");
}
}


I've stepped through the debugger and I know that the instance variable, SongDatabase = null, which is probably causing the error? I previously had a line

SongDatabase SongDatabase = new SongDatabase();
SongDatabase.addNewSong();


instead, but I realised this was creating a new SongDatabase object everytime and wiping what I had stored in there so I had to change it. I'd really appreciate a solution because I have no clue, thanks!

Answer Source

You shouldn't give your instance field the same name as the class because that causes Variable shadowing - Wikipedia says (in part) variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. At the level of identifiers (names, rather than variables), this is known as name masking. And you could define the reference at declaration like

private SongDatabase songDatabase = new SongDatabase();

Then something like

private void run() {
    switch (userInput) {
    case 1: 
        songDatabase.addNewSong();
        break;
    case 2:
        songDatabase.removeSong();
        break;
    case 3:
        songDatabase.sortSongs();
        break;
    default:
        System.out.println("Please enter a valid number.");
        break;
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download