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.
Related Topics
Android Splash Screen Tutorial
Tutorial | 0 Comments
Android Table Layout with columns of equal width
Tutorial | 0 Comments
Android Getting Sound Levels
Open Question | 1 Answer
Java: Smaller/Larger Comparison of Strings - The operator > is undefined for the argument type(s) java.lang.String
Question | 1 Answer
Java: Case Insensitive Equals - String Comparison
Info | 0 Comments
Android Programming: Receive Responce from HTTP POST Request
Tutorial | 0 Comments
PHP: Check Strings with Ctype-Functions for Character Classes
Article | 0 Comments
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.
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:
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