0

Can I use the equals operator to match a case-sensitive String that contains underscore?

str1.trim() == "Aavik_aArjun" 

Or should I use a regex for this simple match as the equals operator is not working?

Mario Codes
  • 689
  • 8
  • 15
Aavik
  • 967
  • 19
  • 48
  • You should always compare strings with `equals()` method not with `==`. – Pradeep Simha Aug 26 '20 at 06:18
  • 1
    equal isn't an operator. equals is a method. if it doesn't return true, than the two Strings aren't equal. it 's that simple – Stultuske Aug 26 '20 at 06:21
  • @Stultuske '==' is an operator and the answer is, that it can't be used for Strings... – Turo Aug 26 '20 at 06:33
  • 1
    @Turo yes, '==' is an operator, but I wasn't talking about that. secondly, it can be used for Strings, it can be used for any type, but it won't always give you the result you expect. – Stultuske Aug 26 '20 at 06:41
  • @Stultuske: Touché :-) – Turo Aug 26 '20 at 06:45
  • @Turo had the OP mentioned the equality (instead of equal) operator, I would have assumed he was talking about == :) – Stultuske Aug 26 '20 at 06:47
  • 1
    Does this answer your question? [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Mario Codes Aug 27 '20 at 12:12

1 Answers1

4

For String (and objects in general) use the .equals() method and not the == operator, as the former compares the references and not the actual content of the Strings.

Mario Codes
  • 689
  • 8
  • 15
Ralph Aouad
  • 414
  • 4
  • 10
  • This does not answer the question. – MC Emperor Aug 26 '20 at 06:50
  • 1
    @MCEmperor possibly, it does. With a bit imagination, you can read the OP's question as: myString == "value" doesn't work. How come? – Stultuske Aug 26 '20 at 08:28
  • 1
    @Stultuske Well, in that case it should be marked as duplicate of [How do I compare Strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) Also, OP seems to be mixing checking strings for equality and checking whether a *substring* occurs (the word "contains" implies that). Imagination is a little subjective. – MC Emperor Aug 26 '20 at 20:29