Write a program to check whether two String objects contain the same data


This Java program checks whether two given strings have the same data (i.e., same characters in the same order).

  • The program defines a public class named "Check_SameData" with a main method that takes no arguments. The main method declares three String variables s1, s2, and s3, with the values "Java Exercise", "Tutor joes", and "Java Exercise", respectively.
  • Then, the program uses the equals method of the String class to check if s1 equals s2 and if s1 equals s3. The boolean values equ1 and equ2 store the results of these checks.
  • Finally, the program prints out whether each pair of strings have the same data by concatenating the string variables and boolean values with the + operator and using System.out.println method to display the result.

Source Code

public class Check_SameData
{
	public static void main(String[] args)
	{
		String s1 = "Java Exercise";
		String s2 = "Tutor joes";
		String s3 = "Java Exercise";
		boolean equ1 = s1.equals(s2);
		boolean equ2 = s1.equals(s3);
		System.out.println("'" + s1 + "' equals '" +s2 + "' ? " + equ1);
		System.out.println("'" + s1 + "' equals '" +s3 + "' ? " + equ2);
	}
}

Output

'Java Exercise' equals 'Tutor joes' ? false
'Java Exercise' equals 'Java Exercise' ? true

Example Programs