Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two strings are equal in value, what is the best method? [duplicate]

Tags:

java

Always confused about this stuff. Anyone can help?

like image 537
user496949 Avatar asked Mar 15 '11 03:03

user496949


People also ask

What is the best way to tell if the following two strings are equal?

Java String equals() Method The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.

How do you compare two strings or values are same?

Using String. equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true. If any character does not match, then it returns false.

What is the best way to compare strings?

The right way of comparing String in Java is to either use equals(), equalsIgnoreCase(), or compareTo() method. You should use equals() method to check if two String contains exactly same characters in same order. It returns true if two String are equal or false if unequal.

What is difference between == equals () and compareTo () method?

The equals() tells the equality of two strings whereas the compareTo() method tell how strings are compared lexicographically.


2 Answers

string1.equals(string2) is the way.

It returns true if string1 is equals to string2 in value. Else, it will return false.

equals reference

like image 172
Mahesh Avatar answered Oct 12 '22 22:10

Mahesh


string1.equals(string2) is right way to do it.

String s = "something", t = "maybe something else";  if (s == t)      // Legal, but usually results WRONG.  if (s.equals(t)) // RIGHT way to check the two strings   /* == will fail in following case:*/  String s1 = new String("abc");  String s2 = new String("abc");   if(s1==s2) //it will return false 
like image 24
Ankur Avatar answered Oct 12 '22 22:10

Ankur