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...