How to Check If String Starts with Specified Word in Java


Here we will learn how to check if a string starts with a specified word in Java.

Source Code

package com.beginner.examples;

public class StringStartsWith {

	public static void main(String[] args) {
		
		String string1 = "Hello World";
		String string2 = "World";
		
		/*
		 * check whether String starts with Hello or not.
		 * Use startsWith method of the String.
		 */
		if(string1.startsWith("Hello")){
			System.out.println("String1 starts with Hello");
		}else{
			System.out.println("String1 does not start with Hello");
		}
		
		if(string2.startsWith("Hello")){
			System.out.println("String2 starts with Hello");
		}else{
			System.out.println("String2 does not start with Hello");
		}

	}

}

Output:

String1 starts with Hello
String2 does not start with Hello
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments