Categories
java String

How to compare two strings in java

In this post, We will learn How to compare two strings in java

It might sounds easy. But we need to take care of few things while comparing two Strings

Avoid ==

If you are newbie to java, This might surprise you

while you use == to compare string it will not check the value of two strings

Instead of that it will check the reference of two Strings

"BeginnersBug" == new String("BeginnersBug") 
// Above check will return false 

In the above snippet even though both the String are equal it will return false because both are not same object

.equals() method

.equlas method will compare two strings with the value irrespective of its object

Even though if it is two different object it will compare the value of two string

"BeginnersBug".equals(new String("BeginnersBug")) 
// Above check will return true

In the above code snippet it will compare two string value and it will return true for the condition

. equalsIgnoreCase() method

equalsIgnoreCase() method will ignore the case while checking the value of two Strings

If you want to check two Strings irrespective of case sensitive you can use this method

"beginnersbug".equalsIgnoreCase(new String("BeginnersBug")) 
// Above method will return true

In the above code snippet equalsIgnoreCase method will ignore the case sensitive. So it is returning true for the statement

Example

public class CompareStringExample {
	public static void main(String[] args) {
		try {
			// Example 1 == Below check will failS
			if ("BeginnersBug" == new String("BeginnersBug")) {
				System.out.println("Example 1 : Both the strings are equal");
			} else {
				System.out.println("Example 1 : Both the strings are not equal");
			}

			// Example 2 .equals()
			if ("BeginnersBug".equals(new String("BeginnersBug"))) {
				System.out.println("Example 2 : Both the strings are equal");
			} else {
				System.out.println("Example 2 : Both the strings are not equal");
			}

			// Example 3 .equalsIgnoreCase()
			if ("beginnersbug".equalsIgnoreCase(new String("BeginnersBug"))) {
				System.out.println("Example 3 : Both the strings are equal");
			} else {
				System.out.println("Example 3 : Both the strings are not equal");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Output
Example 1 : Both the strings are not equal
Example 2 : Both the strings are equal
Example 3 : Both the strings are equal
Reference

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equalsIgnoreCase(java.lang.String)

Related Articles

Convert String to lowercase using java

Print a String in java with example

Leave a Reply

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