Write a program to compare a given string to the specified character sequence


This Java program demonstrates how to compare a string with a specified sequence of characters using the contentEquals() method of the String class.

  • In this program, two strings "Tutor Joes" and "Computer Education" are assigned to the str1 and str2 variables respectively. A CharSequence object cs is also created with the value "Tutor Joes".
  • Then, the contentEquals() method is called on str1 with cs as an argument, and the result is printed using the println() method. Similarly, the contentEquals() method is called on str2 with cs as an argument, and the result is printed.
  • The contentEquals() method returns true if the specified character sequence is equal to the given string, otherwise it returns false.

Source Code

public class Compare_Specified_Char
{
	public static void main(String[] args)
	{
		String str1 = "Tutor Joes";
		String str2 = "Computer Education";
		CharSequence cs = "Tutor Joes";
		System.out.println("Comparing '"+str1+"'"+" and '"+cs+"' : " + str1.contentEquals(cs));
		System.out.println("Comparing '"+str2+"'"+" and '"+cs+"' :"+ str2.contentEquals(cs));
	}
}

Output

Comparing 'Tutor Joes' and 'Tutor Joes' : true
Comparing 'Computer Education' and 'Tutor Joes' :false

Example Programs