user1627774
user1627774

Reputation: 43

Comparing string array in JAVA

I have the following code within a for loop to see if a string equals a search string:

if(Data.coord[i].equals(Data.search))

I've tested the code with exact values i.e if 1=1 and the rest of the code works fine. It just doesn't like the string comparison. The consol gives out this error:

Exception in thread "main" java.lang.NullPointerException
at highercoursework.Search.main(Search.java:16)
at highercoursework.Main.main(Main.java:16)

Thanks

Upvotes: 1

Views: 702

Answers (6)

Pierre
Pierre

Reputation: 59

you can avoid your problem in two ways:

  • In the case coord[i] should not be null

    if (Data.coord[i] != null) {
        if(Data.coord[i].equals(Data.search)) {
    
        }
    } else {
        logger.error("Unexpected Behavior: coord[i] should not be null");
    }
    

Note: You can replace the logger message by a more appropriated code that fit to your requirement.


  • In the case your your coord[i] can be null

comparing in this way won't throw an exception if Data.coord[i] is null. (Assuming Data.search is a constant and can't bu null) So the rules for this case is: use in priority a String object constant to call the method equals.

if (Data.search.equals(Data.coord[i])) {}

Upvotes: 1

Sashi Kant
Sashi Kant

Reputation: 13465

Try this:

if(DATA != null && Data.coord[i].equals(Data.search))

Upvotes: 0

Brian Agnew
Brian Agnew

Reputation: 272337

You have an unpopulated element in your array i.e.

Data.coord[i]

is null. Note that Data.search could be null, but the equals() method will handle this. You just need to perform the lement check first.

Upvotes: 2

vels4j
vels4j

Reputation: 11298

Read this to understand What is a Null Pointer Exception?

if coord[] is initialized properly, value of Data.coord[i] may be null. You can check

if(Data.coord[i] != null && Data.coord[i].equals(Data.search)) {}

Upvotes: 0

Ashwinee K Jha
Ashwinee K Jha

Reputation: 9317

String[] coord = new String[100];

This will mean you can assign something to coord[0] but until you do that coord[0] is null. Hence the null pointer exception.

You can try.

String data= Data.coord[i];
if(data != null && data.equals(Data.search))

Upvotes: 1

Adam Arold
Adam Arold

Reputation: 30548

You should compare the constant to your parameter since it can be null.

For example if Data.search is a constant which you are searching for you should do this:

if(Data.search.equals(Data.coord[i]))

In this case you won't end up trying to call methods on a null reference and you won't need unnecessary null checks either.

Upvotes: 2

Related Questions