Write a program to check whether a given string ends with the contents of another string


This Java program checks if two given strings end with a specified suffix. It defines a public class named "Check_Endswith" with a main method that takes no arguments. The main method declares two String variables str1 and str2 with the values "Java Exercises" and "Java Exercise", respectively. It also declares a String variable e with the value "se", which is the suffix we want to check for.

Then, the program uses the endsWith method of the String class to check if str1 and str2 end with the suffix e. The boolean values ends1 and ends2 store the results of these checks.

Finally, the program prints out whether each string ends with the specified suffix 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_Endswith
{
	public static void main(String[] args)
	{
		String str1 = "Java Exercises";
		String str2 = "Java Exercise";
 
		String e = "se";
		boolean ends1 = str1.endsWith(e);
		boolean ends2 = str2.endsWith(e);
		System.out.println("'" + str1 + "' ends with " +"'" + e + "' ? " + ends1);
		System.out.println("'" + str2 + "' ends with " + "'" + e + "' ? " + ends2);
	}
}

Output

'Java Exercises' ends with 'se' ? false
'Java Exercise' ends with 'se' ? true

Example Programs