Compare two Strings in java - equals() and equalsIgnoreCase()

The first thing that comes to mind is to make the comparison with "==" but that's totally wrong. When I started programming with Java I compared two strings with "==" which tests the equality of objects but not between two strings two characters. Unlike C++,   Java designers created methods in the String class to simplify the language since it is object-oriented.

Comparing String with the equals

The equals() method of the class String tests the equality of values in java or variable contents and returns true if both strings contain the same characters. Here's an example:

String s1="str"; 
String s2="str";
if(s1.equals(s2))
System.out.println("Both Strings are equal");
equals() is case-sensitive(lowercase or uppercase):

String s1="str"; 
String s2="STR";
if(s1.equals(s2))
System.out.println("Both Strings are equal");
In this case, it returns false.

Ignore uppercase with the equalsIgnoreCase()

The equalsIgnoreCase() method avoids passing a String from lowercase to uppercase and vis-vers-that and compares it with equals(), Java offers an equalsIgnoreCase() method that converts characters to lowercase and compares the two strings.
< br />
String s1="str"; 
String s2="STR";
if(s1.equalsIgnoreCase(s2))
System.out.println("Sensitivity to ignored case. The two Strings are equal");

Size comparison

The String class has the length() method that returns the length of the string:

if("string1".length()=="string2".length())
System.out.println("string1 and string2 equal in size");
else if("string1".length()>" string2".length())
System.out.println("string1 is longer");
else
System.out.println("string2 is longer");

What's the difference between equals and "=="

The equals() method tests for equality of values.

new String("test").equals(new String("test"));//--> true
The "==" operator tests the equality of objects, here are a series of errors to avoid:

String s1="trial"; 
String s2="trial";

//they are the same object
s1==s2; --> false

//they are not the same object
s1 == "test"; --> false

//They reference the same object
"test" == "test"; --> true

//the concatenation is considered as a single object
"test" == "your"+"t"; --> true

//the substring() method generates a new object
"test" == "1test".substring(1); --> false

//the replace() method generates a new object
"test" == "Test".replace("T", "t"); --> false
The concatenation returns true because it is called during compilation, unlike substring() and replace() which are called at runtime and a new object will be created that does not equal the other side of the equation.

Commentaires (12)

Connectez-vous pour commenter

Rejoignez la discussion et partagez vos connaissances avec la communauté

JD
Jean Dupont Il y a 2 heures

Excellent tutoriel ! J'ai enfin compris comment utiliser Apache POI correctement.

👍 12 Répondre Signaler
CodeurJava ✓ Auteur • Il y a 1 heure

Merci Jean ! N'hésitez pas si vous avez des questions.