Skip to content

String Comparison in Java

In this article, We going to see the different ways to compare strings in Java. String is most commonly using datatype in java. And String comparison is very naturally used operation.

1. Using “==” operator.

It only checks reference equality, it means if they refers the same object or not.

String str1 = "First";
String str2 = new String("First");
String str3 = "First";
	
System.out.println(str1 == str2);  //false
System.out.println(str1 == str3); //true

In the above example, the str1 is created with literal and str2 is created using new operator – therefore they refer different. On other hand, str3 and str1 is true because the both variable points to same String literal.

Sometimes it looks as if == compares values, this is because when you create any String literal, the JVM first searches for that literal in the String pool, and if it finds a match, that same reference will be given to the new String.

It handles null String as well.

System.out.println(null == null); //true

2. Using equals()

This method compares the String value. Also, if any of the two strings is null, then the method returns false.

String str1 = "First";
String str2 = new String("First");
String str3 = "First";
String str4 = new String("first");
				
System.out.println(str1.equals(str2)); //true
System.out.println(str1.equals(str3)); //true
System.out.println(str3.equals(str4)); //false

3. Using equalsIgnoreCase()

When you want to test your strings for equality in this case-insensitive manner, use the equalsIgnoreCase method of the String class, like this:

String str1 = "First";
String str2 = new String("first");
	
System.out.println(str1.equals(str2)); //true

4. Using compareTo()

Less common way to compare Java strings, and that’s with the String class compareTo method. Each character of both the strings is converted into a Unicode value for comparison.

See also  Remove cookies from a request while logging out - Java

If both the strings are equal then this method returns 0 else it returns positive or negative value. The result is positive if the first string is lexicographically greater than the second string else the result would be negative.

String str1 = "First";  
String str2 = "first"; 
	
System.out.println(str1.compareTo(str2));  // -32

5. Using compareToIgnoreCase()

It is similar to the previous method, except it ignores case:

String str1 = "First";  
String str2 = "first"; 
		
System.out.println(str1.compareToIgnoreCase(str2)); // 0

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.