-1

I have a String[], and a String parameter. I have tested it with other String[] and String, it returned true. However, this one is saying false.

// toFind is a parameter of a function(defined as a String), and fileName is String[]

System.out.println("toFind length is " + toFind.length() + ", fileName length is " + fileName[i].length());
System.out.println(toFind + ", " + fileName[i]);
System.out.println(toFind == fileName[i] + "\n");
toFind length is 19, fileName length is 19
lab.filestrdesc.txt, lab.filestrdesc.txt
false

I know it is not supposed to say false, but it does.. how can I fix it?

  • 4
    Does this answer your question? [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) The problem is `toFind == fileName[i]`, make it `toFind.equals(fileName[i])` – deHaar Mar 04 '20 at 08:52

1 Answers1

1

Strings are instances, so when comparing ==, the hash code of the two instances is compared.
Use equals().

System.out.println(toFind.equals(fileName[i]) + "\n");
yeahseol
  • 377
  • 1
  • 6