+ 1

Is there a method in Java to test if two strings' values are equal?

12th May 2018, 12:16 PM
Ibaadi Jaya
Ibaadi Jaya - avatar
9 Answers
+ 3
The String equals() method comparesthe original content of the string. Itcompares values of string for equality.String class provides two methods: public boolean equals(Object another) compares this string to the specified object.
12th May 2018, 12:25 PM
MsJ
MsJ - avatar
+ 4
String s = "Straight";   String t = "straight"; System.out.println(s.equals(t)); System.out.println(s.equalsIgnoreCase(t)); If you run the above program you will get the following result: false true The first one will return false because of the first letter’s case. equals() doesn’t takes cases seriously. To curb that issue we have equalsIgnoreCase. = = Operator If you have references to compare = = operator comes in handy. Remember it doesn’t compare values. String s = "Straight";   String t = "straight";  String m = new String("Straight");  System.out.println(s == t);  System.out.println(s == m); In the above code, line 2 will try to find the instance available in the String Pool thus referencing itself to ‘s’. Both will become equal, and hence the operator result for it will turn out to be true. For the second sysout display the result will be false because m has become a different instance in the heap. Here’s the result of the above program: true false
12th May 2018, 12:26 PM
MsJ
MsJ - avatar
+ 3
Do we need to create an object to use the method?
12th May 2018, 12:26 PM
Ibaadi Jaya
Ibaadi Jaya - avatar
+ 3
Paul Grasser (string1 == string2) returns "String cannot be converted into boolean"...
12th May 2018, 12:50 PM
Ibaadi Jaya
Ibaadi Jaya - avatar
12th May 2018, 12:31 PM
MsJ
MsJ - avatar
+ 1
if (string1 == string2){ //Code to be executed }
12th May 2018, 12:37 PM
Paul Grasser
Paul Grasser - avatar
0
See this code, it shows the diffetence between == and equals() https://code.sololearn.com/c79tfjeZkWvs/?ref=app
12th May 2018, 12:54 PM
ifl
ifl - avatar
0
str.equals
12th May 2018, 1:31 PM
Mayur Chaudhari
Mayur Chaudhari - avatar