Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is causing my java.lang.NullPointerException error when I try to run this program? [duplicate]

Tags:

java

arrays

My code is this:

public class Main{

    public static void main(String[] args){
        WordGroup wordgroupOne= new WordGroup ("You can discover more about a person in an hour of play than in a year of conversation");
        WordGroup wordgroupTwo= new WordGroup ( "When you play play hard when you work dont play at all");

        String[] quoteOne = wordgroupOne.getWordArray();   
        String[] quoteTwo = wordgroupTwo.getWordArray();

        for (String word : quoteOne){
            System.out.println(word);
        }

        for (String word : quoteTwo){                       
            System.out.println(word);
        }
    }
}

Wordgroup class:

public class WordGroup {
    public String words;

    public WordGroup (String getWords){
        words = words.toLowerCase();
    }

    public String[] getWordArray(){
        return words.split(" ");   
    }
}

It compiles fine but when I try to run it I get the error java.lang.NullPointerException and it highlights "words = words.toLowerCase();" (I'm using blueJ) what is causing this?

When researching it says that this error is when you try to operate on a null set but the WordGroup is not null as it has a string defined in Main.

like image 383
user2973447 Avatar asked Dec 20 '22 21:12

user2973447


1 Answers

Because the default value (see default value section) for every object is null. Since you didn't initialize words, the NPE is thrown.

public WordGroup (String getWords){
   words = words.toLowerCase(); <- here words is null so a NPE is thrown
}

But I think you didn't correctly set up your constructor; it should be :

public WordGroup (String getWords){
   words = getWords.toLowerCase();
}
like image 72
Alexis C. Avatar answered Dec 22 '22 09:12

Alexis C.