Jeeter
Jeeter

Reputation: 6105

comparison of strings throws NullPointerException

I have an array of Strings called letters. When I try to execute the following line of code, I get a NullPointerException.

if(letters[j].equals(tmpst))

Where j is an arbitrary index less than the length of letters

tmpst is a string that is defined as such:

char myChar = theWord.charAt(i);
String tmpst = String.valueOf(myChar);

where theWord is an arbitrary string with length greater than 4.

The full code is:

for (int i = 0; i < theWord.length(); i++) { 
        for (int j = 0; j < letters.length; j++) { 

            char myChar = theWord.charAt(i);
            String tmpst = String.valueOf(myChar);

            if(letters[j].equals(tmpst)) { 
                System.out.println("YOU DIDIT!!! :D");
                newWord = newWord + theWord.charAt(i);
            }

        }

Can someone see what I'm doing wrong?

Thanks.

Upvotes: 0

Views: 2007

Answers (4)

user16141936
user16141936

Reputation: 1

check for !=null first, then use .equals() method..... because null is not a string.so can't user .equals() method

Upvotes: 0

khan
khan

Reputation: 2674

You Need to understand the difference.
For instance , There is a String myString.Now myString == null and myString.equals("") are two different things.
Before using myString.equals("") , you must need to assure that your string is initialized and not null. So ,your this error is coming because of non intialization of your string object at any index.
Try to check it by using myString == null
Feel free to ask if you have any embiguity :)

Upvotes: 0

Malcolm
Malcolm

Reputation: 41510

If the expression letters.length evaluated without problems, then letters[j] is null, this is the only possibility. You can't call methods on null references.

You should write something considering the case if it is null like this:

if (letters[j] != null && letters[j].equals(tmpst)) {

Upvotes: 0

Daniel Pereira
Daniel Pereira

Reputation: 2785

It seems that your array contains some null references. You can use Arrays.toString(letters) to see if it is true.

If you want that your comparisson still works even if your array contains null values, you should change your code to be like this:

if(tmpst.equals(letters[j]))

Upvotes: 1

Related Questions