24 Votes

Java/Android: String comparison s1==s2 does not work

Question by Guest | Last update on 2022-04-18 | Created on 2013-09-16

I am trying to compare two strings with each other using the operator "==" in Java for Android. I have the following code:

String s1 = new String("abc");
String s2 = new String("abc");

if (s1 == s2) {
   // the same?!
} else {
   // not the same?!
}

I do not know why, but this condition always returns "false" independent from whether s1 and s2 are equal or not.

What is my mistake here? In all other programming languages I know and I am familiar to, it is working exactly like that.

ReplyPositiveNegative
2Best Answer2 Votes

In Java/Android, a string is an object. When using the operator "==", Java is checking whether the two objects are identical and not whether their content is identical. Because in your example, the objects "s1" and "s2" are not identical, the if-condition always returns "false".

In order to compare the content of two strings, you can use the method .equals(Object obj) for your comparison:

String s1 = new String("abc");
String s2 = new String("abc");
String s3 = s1;
 
if (s1.equals(s2)) { }  // true
if (s1 == s2) { }       // false 
if (s1 == s3) { }       // true

Additionally, in this example, I have declared the String s3 and set it to s1. In this case, actually, the objects s1 and s3 are identical so that the condition with "==" will be "true" here.
Last update on 2022-04-18 | Created on 2013-09-16

ReplyPositive Negative
Reply

Related Topics

Android Splash Screen Tutorial

Tutorial | 0 Comments

Android Getting Sound Levels

Open Question | 1 Answer

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.