Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the responsive-lightbox domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114

Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the hueman domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114
String methods - startsWith and endsWith - Testingpool

String methods – startsWith and endsWith

In this post, we will discuss 2 methods which are endsWith() and startsWith().

Let’s understand with examples.

boolean endsWith(String suffix):

This method checks if string ends with specified suffix. If ends with specified  suffix then returns true else false.

public class StringMethodsEx {

	public static void main(String[] args) {
		
		String val1 = "Hello world!!";
		
		System.out.println(val1.endsWith("!!"));  //returns true
		System.out.println(val1.endsWith("World"));  //returns false
	}
}
Output:
true
false

 

startswith() :

This method returns true if string starts with specified prefix, else will return false. It has 2 types of implementations.

1. boolean startsWith(String prefix): 

It checks if string starts with specified prefix or not.

Note: It will return true if the argument is an empty string.
public class StringMethodsEx {

	public static void main(String[] args) {
		
		String val1 = "Hello world!!";	
		System.out.println(val1.startsWith("Hello"));  //returns true
		System.out.println(val1.endsWith("World"));  //returns false
		
	}
}
Output:
true
false

boolean startsWith(String prefix,int toffset):

This method returns true if string starts with specified prefix starting from the given index.

public class StringMethodsEx {

	public static void main(String[] args) {
		
		String val1 = "Hello world!!";	
		System.out.println(val1.startsWith("Hello", 0));  //returns true
		System.out.println(val1.startsWith("Hello",4));  //returns false as Hello string start at 0	
	}
}
Output:
true
false
Ask Question
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...