2

Trying to find a string "needle" in an Object array. But using .equals to compare gives me an error. But using == works. Why? I thought I had to use .equals to compare objects/strings.

Code that runs with ==

public class ANeedleInTheHaystack_8 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Object[] haystack2 = {"283497238987234", "a dog", "a cat", "some random junk", "a piece of hay", "needle", "something somebody lost a while ago"};
        Object[] haystack1 = {"3", "123124234", null, "needle", "world", "hay", 2, "3", true, false};
        System.out.println(findNeedle(haystack2));
        System.out.println(findNeedle(haystack1));
    }

    public static String findNeedle(Object[] haystack) {

        for(int i = 0 ; i < haystack.length ; i ++) {
            if(haystack[i] == "needle") {
                return String.format("found the needle at position %s", i);
            }
        }
        return null;
    }

}

Out put

found the needle at position 5
found the needle at position 3

and code that doesn't run with .equals

public class ANeedleInTheHaystack_8 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Object[] haystack2 = { "283497238987234", "a dog", "a cat", "some random junk", "a piece of hay", "needle",
                "something somebody lost a while ago" };
        Object[] haystack1 = { "3", "123124234", null, "needle", "world", "hay", 2, "3", true, false };
        System.out.println(findNeedle(haystack2));
        System.out.println(findNeedle(haystack1));
    }

    public static String findNeedle(Object[] haystack) {
        for(int i = 0 ; i < haystack.length ; i ++) {
            if(haystack[i].equals("needle")) {
                return String.format("found the needle at position %s", i);
            }
        }
        return null;
    }

}

out put

found the needle at position 5
Exception in thread "main" java.lang.NullPointerException
    at ANeedleInTheHaystack_8.findNeedle(ANeedleInTheHaystack_8.java:15)
    at ANeedleInTheHaystack_8.main(ANeedleInTheHaystack_8.java:10)

Seems like I am only getting an error when I am comparing with null. Can .equals compare an object with null?

coco
  • 59
  • 3
  • 3
    `.equals` can only be used if you know the calling object is not null. You could make it work in your code by switching to `"needle".equals(haystack[i])` since `"needle"` is obviously always going to be non-null – resueman Sep 04 '19 at 22:59
  • Use `Objects.equals` instead. It will handle `null` values gracefully. – Johannes Kuhn Sep 04 '19 at 23:05

2 Answers2

1

Change your method findNeedle like this:

    public static String findNeedle(Object[] haystack) {
        for(int i = 0 ; i < haystack.length ; i ++) {
            if("needle".equals(haystack[i])) {
                return String.format("found the needle at position %s", i);
            }
        }
        return null;
    }

You can't call method of null, but equals method can check if a object is equal to null.

iNardex
  • 1,132
  • 1
  • 5
  • 7
0

using == works. Why? I thought I had to use .equals to compare objects/strings.

In most scenarios, you probably should use .equals() compare objects and strings, but it is totally valid (and sometimes exactly what you want) to use ==.

Using == will compare the object references – do these two variables point at the same underlying object? Using .equals() will evaluate whether the objects are equivalent.

Kaan
  • 5,434
  • 3
  • 19
  • 41