Java Program example to demonstrate String contentEquals method

Program

public class StringContentEquals
{
	public static void main(String[] args)
	{
		String str1 = "welcome to oodlescoop";
		String str2 = "welcome to oodlescoop";
		String str3 = "welcome to tutorials";
		System.out.print("Content of \"" + str1 + "\" and \"" + str2 + "\" equal: ");
		System.out.println(str1.contentEquals(str2));
                System.out.print("Content of \"" + str1 + "\" and \"" + str3 + "\" equal: ");
		System.out.println(str1.contentEquals(str3));
	}
}

Purpose

This Java program demonstrates how to use the contentEquals method of the String class to compare the contents of two strings.

1. Class Definition

public class StringContentEquals
  • Defines the class StringContentEquals.

2. Main Method

public static void main(String[] args)
  • Entry point for the program.

3. Define Strings

String str1 = "welcome to oodlescoop";
String str2 = "welcome to oodlescoop";
String str3 = "welcome to tutorials";
  • str1: A string with content "welcome to oodlescoop".
  • str2: Identical to str1.
  • str3: A string with different content "welcome to tutorials".

4. Compare Strings Using contentEquals

System.out.print("Content of \"" + str1 + "\" and \"" + str2 + "\" equal: ");
System.out.println(str1.contentEquals(str2));
System.out.print("Content of \"" + str1 + "\" and \"" + str3 + "\" equal: ");
System.out.println(str1.contentEquals(str3));
  • contentEquals Method:
    • Compares the content of the current string (str1) with the argument string.
    • Returns true if the two strings are exactly identical (character by character), otherwise false.

Detailed Explanation of Comparisons

1. Compare str1 and str2

str1.contentEquals(str2)
  • str1: "welcome to oodlescoop".
  • str2: "welcome to oodlescoop".
  • Both strings are identical.
  • Result: true.
  • Output:
    Content of "welcome to oodlescoop" and "welcome to oodlescoop" equal: true
    

2. Compare str1 and str3

str1.contentEquals(str3)
  • str1: "welcome to oodlescoop".
  • str3: "welcome to tutorials".
  • The strings differ in content.
  • Result: false.
  • Output:
    Content of "welcome to oodlescoop" and "welcome to tutorials" equal: false
    

Key Points About contentEquals

  1. Exact Match:

    • The method performs an exact match of characters in both strings.
    • Case-sensitive.
    • Checks the order and number of characters.
  2. Strict Comparison:

    • Does not allow partial matches or case-insensitive matches.

Output

Content of "welcome to oodlescoop" and "welcome to oodlescoop" equal: true
Content of "welcome to oodlescoop" and "welcome to tutorials" equal: false