APCoding
APCoding

Reputation: 301

Null Pointer Exception in Java when using String Arrays

I have a piece of code where the program compares the value of two arrays of strings. I am getting a java.lang.NullPointerException, even though I initialized both arrays. Here is the relevant code:

String[] functions=new String [inputs+1];
int funCounter=0;
for (int a=0;a<2;a++)
{
    for (int b=0;b<2;b++)
    {
        if (tokenizedString[b].equals(keywords[a])&&keywords[a].equals("add"))
        {
            System.out.println("Yay");
            functions[funCounter]="add";
            funCounter++;
        }
        }
    }

This is where I inialize tokenizedString:

String[] tokenizedString;
    tokenizedString=new String[2];

tokenizedString is added to a Scanner in stream here:

StringTokenizer st = new StringTokenizer(input," ");

And here is where I initialize keywords:

String[] keywords;
    keywords=new String[2];

Any ideas? Thanks!

Upvotes: 1

Views: 1699

Answers (1)

Anshuman
Anshuman

Reputation: 841

While you are accessing tokenizedString[n], the string array will give you the nth element. If the nth element is not initialized, for object arrays it will be defaulted to null.

A better way to avoid null checks in this case will be to switch places of the string values if you are sure that the other one will never be null. So instead of:

 tokenizedString[b].equals(keywords[a])

use:

 keywords[a].equals(tokenizedString[b])

Upvotes: 1

Related Questions