-8

I have,
String str1 = "StringA";
String str2 = "StringA";

Now, I do

(str1 == str2)

Sometimes it doesn't match the strings and returns false

But str1.equals(str2) always returns true

What I'm missing here?
I cannot always use equals as my String can be null also.

Thanks!

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
bram
  • 1,268
  • 2
  • 12
  • 20

2 Answers2

3

== compares references not the content

To compare strings you need to use String#equals:

.equals(); //If you  consider the case
.equalsIgnoreCase(); //If you not consider the case  
PSR
  • 39,804
  • 41
  • 111
  • 151
1

== compares the exact values. So it compares if the primitive values are the same,

.equals() calls the comparison method of objects, which will compare the actual objects pointed by the references. In the case of Strings, it compares each character to see if they're equal.

Read more here :


Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307