Objective

One of the fundamentals string operation in java is to compare strings. To give an overview, a string is composed of characters. This section objective is to dive in on how to compare the quality of Strings.

We will be leveraging some of the inherent method String class to accomplish the comparison of Strings.

Our objective on this example is how to compare two strings in terms of  equality on its character sequences. One important note to consider is that do not use the = operator to test for equality since we are dealing with Objects which is an inherent property of String. Instead we use the equals method of String class.

String Comparison Example

This example, deals with comparison of two strings. We also have provided a mechanism to compare string regardless of cases. The example below contains wide variety of solutions in comparing Strings.

package com.javatutorialhq.java.examples;

import static java.lang.System.*;

/*
 * This example source code demonstrates 
 * on how to compare two strings in java
 */

public class StringCompareExample {

	public static void main(String[] args) {
		// declare String object
		String strValue = "test string";
		// check equality of String using compareTo
		if(strValue.compareTo("test string")==0){
			out.println("string is equal using compareto");
		}
		// check equality using compareToIgnoreCase which ignore case
		if(strValue.compareToIgnoreCase("Test String")==0){
			out.println("string is equal using compareto regardless of case");
		}
		// check equality using equals method of String class
		if(strValue.equals("test string")){
			out.println("String is equal using equals method");
		}
		// check equality using equalsIgnoreCase which ignore case
		if(strValue.equalsIgnoreCase("Test String")){
			out.println("String is equal using equalsIgnoreCase regardless of case");
		}
		// check equality normalizing first the case of characters
		if(strValue.toLowerCase().equals("Test String".toLowerCase())){
			out.println("String is equal");
		}

	}

}

 String Comparison Sample Output

Compiling and running the code above would yield the following result on the console.

string is equal using compareto
string is equal using compareto regardless of case
String is equal using equals method
String is equal using equalsIgnoreCase regardless of case
String is equal

Suggested Reading List