The String class provides built-in methods for accessing, searching, comparing and manipulating text. These methods simplify string processing.
- String indexing starts from zero.
- String objects are immutable, so operations do not modify the original string.
Example: Demonstrating commonly used String methods.
class Geeks {
public static void main(String[] args)
{
String s = "Hello World";
// Accessing and extracting
System.out.println(s.length());
System.out.println(s.charAt(6));
System.out.println(s.substring(6));
// Searching and comparing
System.out.println(s.indexOf("World"));
System.out.println(s.equals("Hello World"));
// Manipulating
System.out.println(s.toUpperCase());
System.out.println(s.replace("World", "Java"));
}
}
Output
11 W World 6 true HELLO WORLD Hello Java
Explanation: The program demonstrates string extraction, searching, comparison and manipulation using built-in methods. The original string remains unchanged.
Commonly Used Java String Methods
The following table categorizes String methods based on their functionality, with links to relevant GeeksforGeeks articles for detailed explanations.
1. Accessing and Extracting Methods
These methods retrieve the length, individual characters or portions of a string.
Method | Description |
|---|---|
Returns the number of UTF-16 code units. | |
Returns the char value at the specified index. | |
Extracts text from the specified index to the end. | |
Extracts text within a range, excluding the end index. |
2. Searching Methods
These methods locate characters or substrings and check whether specific text exists.
Method | Description |
|---|---|
Returns the first occurrence index or -1 if not found. | |
Returns the last occurrence index or -1 if not found. | |
Checks whether a character sequence exists. | |
Checks whether the string begins with a specified prefix. | |
Checks whether the string ends with a specified suffix. |
3. Comparing Methods
These methods compare string contents and lexicographical ordering.
Method | Description |
|---|---|
Checks whether two strings have identical contents. | |
Compares string contents while ignoring case. | |
Compares strings lexicographically. | |
Compares strings lexicographically, ignoring case. |
4. Manipulation Methods
These methods perform text transformations without modifying the original string.
Method | Description |
|---|---|
Joins two strings. | |
Converts text to lowercase. | |
Converts text to uppercase. | |
Removes leading and trailing characters with values up to U+0020. | |
Removes leading and trailing whitespace as defined by Java. | |
Replaces occurrences of specified characters or sequences. |