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


This program checks if a given string starts with a specified substring. Here's a brief explanation of the code:

  • The program starts by defining two strings, str1 and str2, and a substring start.
  • The startsWith() method is used to check if str1 and str2 start with the substring start. This method returns a boolean value (true if the string starts with the specified substring, false otherwise).
  • The results of the checks are printed to the console.

Source Code

public class Check_Startswith
{    
	public static void main(String[] args)
	{
		String str1 = "Orange is Favorite Fruits";
		String str2 = "Grapes is also my favorite Fruits";
 
		String start = "Grapes";
 
		boolean s1 = str1.startsWith(start);
		boolean s2 = str2.startsWith(start);
 
		System.out.println("\""+str1 + "\" starts with \"" +start + "\" ? " + s1);
		System.out.println("\""+str2 + "\" starts with \"" +start + "\" ? " + s2);
	}
}

Output

"Orange is Favorite Fruits" starts with "Grapes" ? false
"Grapes is also my favorite Fruits" starts with "Grapes" ? true

Example Programs