Java String startsWith() and endsWith() Methods With Examples
The String class in Java is an immutable and non-primitive data type that is used to store the characters of the sequence. The string is non-primitive datatype because, during the initialization of the string variable, it refers to an object that contains methods that can perform several different kinds of operations, but according to the definition of the primitive datatype, they are not considered as the object and store the data in the stack memory. In this article, we will discuss the endsWith() method and the startsWith() method of the String class in java.
Let us discuss both the methods individually:
- endsWith() Method in java
- startsWith() Method
Method 1: endsWith() method
This method of the String class checks whether the given string ends with the specified string suffix or not.
Syntax:
endsWith(String suffix)
Parameter: This method takes one parameter that is of string type..
Return type: This method returns a boolean value true or false. the i.e string ends with a specified suffix or not.
Example:
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
String first = "Geeks for Geeks" ;
String suffix = "kse" ;
System.out.println(first.endsWith(suffix));
suffix = "s" ;
System.out.println(first.endsWith(suffix));
}
}
|
Method 2: startsWith() method
This method of the String class checks whether the given string starts with the specified string prefix or not.
Syntax:
startsWith(String prefix)
Parameter: This method takes one parameter that is of string type..
Return type: This method returns a boolean value true or false. the i.e string ends with a specified prefix or not.
Examples:
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
String first = "Geeks for Geeks" ;
String prefix = "se" ;
System.out.println(first.startsWith(prefix));
prefix = "Gee" ;
System.out.println(first.startsWith(prefix));
}
}
|
Last Updated :
27 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...