In Java, a String is more than just a sequence of characters; it is an object that comes packed with powerful built-in tools. Whether you are validating a user's email, parsing data from a file, or formatting text for a UI, these methods do the heavy lifting for you.
Java String Methods
Method
Description
Example
length()
Returns the length of the string.
"Hello".length() returns 5
charAt(int index)
Returns the character at the specified index.
"Hello".charAt(0) returns 'H'
isEmpty()
Returns true if the string is empty.
"".isEmpty() returns true
toUpperCase()
Converts the string to uppercase.
"hello".toUpperCase() returns "HELLO"
toLowerCase()
Converts the string to lowercase.
"HELLO".toLowerCase() returns "hello"
equals(Object obj)
Compares the string to the specified object.
"hello".equals("world") returns false
equalsIgnoreCase(String anotherString)
Compares the string to another string, ignoring case.
"hello".equalsIgnoreCase("HELLO") returns true
compareTo(String anotherString)
Compares two strings lexicographically.
"abc".compareTo("def") returns a negative integer
compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case.
"ABC".compareToIgnoreCase("abc") returns 0
startsWith(String prefix)
Tests if the string starts with the specified prefix.
"hello".startsWith("he") returns true
endsWith(String suffix)
Tests if the string ends with the specified suffix.
"hello".endsWith("lo") returns true
contains(CharSequence s)
Returns true if the string contains the specified sequence of characters.
"hello".contains("ell") returns true
indexOf(int ch)
Returns the index within the string of the first occurrence of the specified character.
"hello".indexOf('l') returns 2
lastIndexOf(int ch)
Returns the index within the string of the last occurrence of the specified character.
"hello".lastIndexOf('l') returns 3
substring(int beginIndex)
Returns a substring of the string, starting at the specified index.
"hello".substring(2) returns "llo"
substring(int beginIndex, int endIndex)
Returns a substring of the string, starting at the specified begin index and ending before the specified end index.
"hello".substring(1, 4) returns "ell"
replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of the specified character with another character.
Returns a string whose value is this string, with leading and trailing whitespace removed.
" hello ".trim() returns "hello"
Understanding String Immutability
Before diving into individual methods, it is vital to remember that Java Strings are immutable. This means once a String object is created, it cannot be changed. When you use a method like toUpperCase() or replace(), you aren't changing the original string; you are creating a brand new one with the modifications.
Developer Tip: Since strings are immutable, they are inherently thread-safe. You can share them across different parts of your program without worrying about one thread changing the value while another is reading it.
Comparing Strings: The Right Way
One of the most common tasks in Java is checking if two strings are equal. While it's tempting to use ==, this usually leads to bugs.
Common Mistake: Using == to compare string content. In Java, == checks if two variables point to the same memory location (reference equality), not if they contain the same text. Always use .equals() for content comparison.
Best Practice: To avoid a NullPointerException, if you are comparing a variable to a known constant, call the method on the constant. For example: "ADMIN".equals(userRole) is safer than userRole.equals("ADMIN").
Searching and Extracting Content
Often, you only need a portion of a string. The substring() method is perfect for this. Remember that Java uses 0-based indexing, meaning the first character is at position 0.
Watch Out: In substring(startIndex, endIndex), the endIndex is exclusive. This means "Java".substring(0, 3) returns "Jav", not "Java".
Cleaning Up Data
When processing user input—like a username or email address—users often accidentally include extra spaces. The trim() method (or strip() in Java 11+) is essential for cleaning this data before saving it to a database.
Developer Tip: While trim() is the classic method, Java 11 introduced strip(), which is "Unicode-aware." If your application supports international characters, strip() is generally the better choice.
Splitting and Replacing
The split() and replaceAll() methods are extremely powerful because they use Regular Expressions (Regex). This allows you to perform complex pattern matching.
Example: Counting words in a sentence
String text = "Learn Java step by step";
String[] words = text.split(" ");
int wordCount = words.length; // Result: 5
Watch Out: Because split() uses Regex, certain characters like ., |, and * are "special." If you want to split a string by a literal period, you must escape it: split("\\.").