Method Description Return Type
charAt(int index) Returns the character at the specified char
index
codePointAt(int index) Returns Unicode code point at specified int
index
codePointBefore(int index) Returns Unicode code point before int
specified index
codePointCount(int beginIndex, int Returns the number of Unicode code int
endIndex) points in the specified range
compareTo(String anotherString) Compares two strings lexicographically int
compareToIgnoreCase(String str) Compares two strings lexicographically, int
ignoring case
concat(String str) Concatenates the specified string to the String
end
contains(CharSequence s) Checks if the string contains the boolean
specified sequence
contentEquals(CharSequence cs) Compares string content with boolean
CharSequence
contentEquals(StringBuffer sb) Compares string content with boolean
StringBuffer
copyValueOf(char[] data) Returns a string from the character String
array
endsWith(String suffix) Checks if the string ends with the given boolean
suffix
equals(Object anObject) Checks if two strings are equal boolean
equalsIgnoreCase(String Compares strings ignoring case boolean
anotherString)
format(String format, Object... Returns formatted string using specified String
args) format and arguments
getBytes() Encodes string into byte array byte[]
getBytes(String charsetName) Encodes string using given charset byte[]
getChars(int srcBegin, int srcEnd, Copies characters into a char array void
char[] dst, int dstBegin)
hashCode() Returns the hash code for the string int
indexOf(int ch) Returns the index of first occurrence of int
character
indexOf(int ch, int fromIndex) Returns the index of character from int
specific index
indexOf(String str) Returns index of first occurrence of int
substring
indexOf(String str, int fromIndex) Returns index of substring from specific int
index
intern() Returns canonical representation of String
string from string pool
isEmpty() Checks if the string is empty boolean
isBlank() (Java 11+) Checks if the string is empty or contains boolean
only whitespace
join(CharSequence delimiter, Joins elements with a delimiter String
CharSequence... elements)
lastIndexOf(int ch) Returns last index of character int
lastIndexOf(int ch, int fromIndex) Returns last index from specific index int
lastIndexOf(String str) Returns last index of substring int
lastIndexOf(String str, int Returns last index of substring from int
fromIndex) index
length() Returns the length of the string int
lines() (Java 11+) Returns a stream of lines from the string Stream<String>
matches(String regex) Tells if string matches the regex boolean
offsetByCodePoints(int index, int Returns index after moving offset code int
codePointOffset) points
regionMatches(boolean Tests if substring matches another boolean
ignoreCase, int toffset, String region
other, int ooffset, int len)
repeat(int count) (Java 11+) Returns string repeated count times String
replace(char oldChar, char Replaces characters in string String
newChar)
replace(CharSequence target, Replaces target subsequence String
CharSequence replacement)
replaceAll(String regex, String Replaces all matches of regex String
replacement)
replaceFirst(String regex, String Replaces first match of regex String
replacement)
split(String regex) Splits string by regex String[]
split(String regex, int limit) Splits with limit on number of String[]
substrings
startsWith(String prefix) Checks if string starts with prefix boolean
startsWith(String prefix, int Checks if substring starts with prefix boolean
toffset)
strip() (Java 11+) Removes leading and trailing String
whitespaces
stripLeading() (Java 11+) Removes only leading whitespaces String
stripTrailing() (Java 11+) Removes only trailing whitespaces String
subSequence(int beginIndex, int Returns a character sequence from CharSequence
endIndex) string
substring(int beginIndex) Returns substring from index to end String
substring(int beginIndex, int Returns substring between two indexes String
endIndex)
toCharArray() Converts string into character array char[]
toLowerCase() Converts all characters to lowercase String
toLowerCase(Locale locale) Converts to lowercase using specific String
locale
toUpperCase() Converts all characters to uppercase String
toUpperCase(Locale locale) Converts to uppercase using specific String
locale
toString() Returns the string itself String
trim() Removes leading and trailing String
whitespaces
valueOf(boolean b) Returns string representation of boolean String
valueOf(char c) Returns string of character String
valueOf(char[] data) Converts char array to string String
valueOf(int i) (and other Converts int, long, double, etc., to string String
primitives)
Note:
Some methods like isBlank(), lines(), repeat(), strip() are available from Java
11 onwards.
valueOf() is overloaded to work with various data types.
Let’s discuss the most commonly used string methods in Java:
1. length()
This string method in Java returns the total number of characters present in a string,
including spaces and special characters. It is one of the most important string methods
in Java and is widely used in input validation, loops, and string size checks.
Syntax:
[Link]();
2. charAt(int index)
This string function in Java returns the character located at the specified index
(starting from 0). It is helpful when analyzing characters in a string individually, such
as in string parsing or pattern matching.
Syntax:
[Link](index);
3. substring(int beginIndex, int endIndex)
This important string method in Java extracts a part of the string starting from
beginIndex up to, but not including, endIndex. It's used for trimming strings,
extracting specific data, or removing prefixes/suffixes.
Syntax:
[Link](beginIndex, endIndex);
4. equals(String anotherString)
This java string method checks whether two strings have the same sequence of
characters. It is case-sensitive and returns a boolean value (true or false).
Syntax:
[Link](anotherString);
5. toUpperCase()
This string function of Java converts all characters in a string to uppercase. It’s
especially useful for standardizing text for case-insensitive comparisons or formatting
purposes.
Syntax:
[Link]();
6. trim()
This java string method removes all leading and trailing whitespaces from a string.
It’s widely used for cleaning input data before storage or comparison.
Syntax:
[Link]();
Example:
public class Example6 {
public static void main(String[] args) {
String msg = " Hello Java ";
[Link]("Before: [" + msg + "]");
[Link]("After: [" + [Link]() + "]");
Run Code
Output:
Before: [ Hello Java ]After: [Hello Java]
7. replace(char oldChar, char newChar)
This string function of Java returns a new string by replacing all occurrences of
oldChar with newChar. It’s commonly used in formatting and cleaning operations.
Syntax:
[Link](oldChar, newChar);
Example:
public class Example7 {
public static void main(String[] args) {
String text = "banana";
[Link]([Link]('a', 'o'));
}
}
Run Code
Output:
bonono
8. split(String regex)
This string method in Java splits the string around matches of the given regular
expression and returns an array of substrings. It’s used in parsing, especially when
dealing with CSV, logs, or user inputs.
Syntax:
[Link](regex);
Example:
public class Example8 {
public static void main(String[] args) {
String data = "apple,banana,grape";
String[] fruits = [Link](",");
for (String fruit : fruits) {
[Link](fruit);
Run Code
Output:
apple
banana
grape
9. contains(CharSequence s)
This java string method checks if the specified character sequence exists within the
string. It returns true or false. Commonly used in search or filtering operations.
Syntax:
[Link](sequence);
Example:
public class Example9 {
public static void main(String[] args) {
String message = "Welcome to Java World";
[Link]([Link]("Java"));
Run Code
Output:
true
10. equalsIgnoreCase(String anotherString)
This string function in Java compares two strings ignoring case differences. It returns
true if both strings have the same characters regardless of case.
Syntax:
[Link](anotherString);
Example:
public class Example10 {
public static void main(String[] args) {
String a = "Admin";
String b = "admin";
[Link]([Link](b));
}
}
Run Code
Output:
true
11. indexOf(String str)
This important string method in Java returns the index of the first occurrence of the
specified substring. If the substring is not found, it returns -1.
Syntax:
[Link](substring);
Example:
public class Example11 {
public static void main(String[] args) {
String name = "Sundar Pichai";
[Link]([Link]("Pichai"));
Run Code
Output:
12. startsWith(String prefix)
This string method in Java checks if the string starts with the specified prefix. It’s
often used in filtering data like filenames, URLs, etc.
Syntax
[Link](prefix);
Example:
public class Example12 {
public static void main(String[] args) {
String filename = "[Link]";
[Link]([Link]("report"));
Run Code
Output:
true
13. endsWith(String suffix)
This string function of Java checks if the string ends with a specific suffix. It is
commonly used to validate file extensions, domain names, etc.
Syntax:
[Link](suffix);
Example:
public class Example13 {
public static void main(String[] args) {
String url = "[Link]";
[Link]([Link](".com"));
Run Code
Output:
true
14. replaceAll(String regex, String replacement)
This java string method replaces each substring that matches the given regex with the
specified replacement. It’s widely used in sanitization, formatting, and data cleaning.
Syntax:
[Link](regex, replacement);
Example:
public class Example14 {
public static void main(String[] args) {
String messy = "abc123xyz456";
[Link]([Link]("[0-9]", ""));
Run Code
Output:
abcxyz
15. isEmpty()
This important string method in Java checks if the string has a length of 0. It’s
frequently used in form validation and input checks.
Syntax:
[Link]();
Example:
public class Example15 {
public static void main(String[] args) {
String input = "";
[Link]([Link]());
}
Run Code
Output:
true
Java String Methods Example
Below is an example program that combines multiple Java string methods:
public class RealWorldStringExample {
public static void main(String[] args) {
String fullName = " virendra soni ";
String email = "info@[Link]";
// Step 1: Trim unwanted spaces
fullName = [Link]();
// Step 2: Capitalize first letter of each word
String[] words = [Link](" ");
StringBuilder formattedName = new StringBuilder();
for (String word : words) {
if (![Link]()) {
[Link]([Link]([Link](0)))
.append([Link](1).toLowerCase())
.append(" ");
}
// Step 3: Validate email domain
boolean isWsCubeEmail = [Link]("@[Link]");
// Step 4: Final output
[Link]("Formatted Name: " + [Link]().trim());
[Link]("Is official email? " + isWsCubeEmail);
Run Code
Output:
Formatted Name: Virendra Soni
Is official email? true
Explanation:
This program first trims the extra spaces from the user's name using trim(), then uses
split() and charAt() along with substring() and toUpperCase() to format the name
properly. After that, it checks if the email ends with a specific domain using
endsWith().
Important Points to Know About Java String Methods & Functions
1. Strings in Java are Immutable
Whenever you call a string method like replace() or toUpperCase(), it doesn't modify
the original string. Instead, it returns a new string object. Always assign the result to a
new variable (or back to the same one) if you want to use the modified value.
2. Use .equals() for String Comparison, Not ==
The == operator checks reference equality (whether both strings point to the same
memory location), not value equality. To compare string contents, always
use .equals() or .equalsIgnoreCase().
3. Watch Out for NullPointerException
Calling a method like [Link]() or [Link]("value") on a null string will throw a
NullPointerException. To avoid this, use "value".equals(str) instead — this is null-
safe.
4. Regex in split(), replaceAll(), and matches()
Methods like split() and replaceAll() use regular expressions. Symbols like . and |
have special meanings, so escape them if you’re using them as literals (e.g., split("\\.")
for splitting on a dot).
5. Prefer isBlank() Over isEmpty() (Java 11+)
isEmpty() returns true only if the string length is zero, while isBlank() also returns
true for strings containing only whitespaces. For real-world form validations,
isBlank() is often more accurate.
6. Use StringBuilder for Repeated Modifications
If you're performing multiple modifications (e.g., in a loop), avoid using + with
strings. Instead, use StringBuilder or StringBuffer for better performance and memory
efficiency.
7. Method Chaining Works but Can Get Messy
While chaining methods like [Link]().toLowerCase().replace(" ", "") is possible, too
much chaining without clarity can reduce readability. Use meaningful intermediate
variables if needed.