java String

String startsWith() and endsWith() in Java Code With Examples

Table of Contents

Program

public class StringStartsEnds
{
	public static void main(String[] args)
	{
		String s1 = "this is java";
		System.out.println(s1.startsWith("this"));
		System.out.println(s1.endsWith("java"));
		System.out.println(s1.startsWith("is"));
		
	}

}

Output

     true
     true
     false

Description

public boolean startsWith​(String prefix)

Tests if this string starts with the specified prefix.

Parameters:

prefix – the prefix.

Returns:

true if the character sequence represented by the argument is a prefix of the character sequence represented by this string; false otherwise. Note also that true will be returned if the argument is an empty string or is equal to this String object as determined by the equals(Object) method.

Since:

1.0

public boolean endsWith​(String suffix)

Tests if this string starts with the specified suffix.

Parameters:

suffix – the suffix.

Returns:

true if the character sequence represented by the argument is a suffix of the character sequence represented by this object; false otherwise. Note that the result will be true if the argument is the empty string or is equal to this String object as determined by the equals(Object) method.