A String is much more than a container for text. The String class provides a rich set of methods for examining, transforming, searching, extracting, and comparing text. Once you become comfortable with these methods, many everyday programming tasks become surprisingly simple.
The important thing to remember is that String objects are immutable. String methods do not modify the original String. Methods that appear to change text return another String containing the requested result.
Why String Methods Matter
Imagine processing a customer's name received from a web form. You may need to remove unwanted spaces, convert the name to a consistent case, check its length, search for a particular character, or replace part of the text. Instead of manually writing loops for every operation, Java provides ready-to-use String methods.
String name = " Priya Sharma "; System.out.println(name.trim()); System.out.println(name.length()); System.out.println(name.toUpperCase());
Each method performs a specific operation, making the code easier to read and maintain.
length()
The length() method returns the number of characters represented by the String.
String language = "Java"; System.out.println(language.length());
Output:
4
Spaces are also counted as characters.
String text = "Java Programming"; System.out.println(text.length());
The space between Java and Programming contributes to the length.
For a String, use length(). For an array, length is a field. Do not confuse the two.
charAt()
The charAt() method returns the character located at a specified zero-based index.
String language = "Java"; System.out.println(language.charAt(0)); System.out.println(language.charAt(3));
Output:
J a
Because indexing begins at zero, the first character is at index 0, not index 1.
Calling charAt() with an index outside the valid range causes a StringIndexOutOfBoundsException. Always make sure the index is between 0 and length() - 1.
toUpperCase()
The toUpperCase() method returns a new String with characters converted to uppercase according to the applicable locale rules.
String language = "Java Programming"; String result = language.toUpperCase(); System.out.println(result);
Output:
JAVA PROGRAMMING
The original value of language remains unchanged because String is immutable.
toLowerCase()
The toLowerCase() method returns a lowercase representation of the string.
String language = "JAVA"; System.out.println(language.toLowerCase());
Output:
java
A useful real-world application is normalizing user input before performing case-insensitive processing.
trim()
The trim() method removes leading and trailing characters that are considered whitespace by the method. It does not remove whitespace occurring in the middle of the string.
String name = " Rahul "; System.out.println(name.trim());
Output:
Rahul
The spaces between words are preserved.
String name = " Rahul Kumar "; System.out.println(name.trim());
Output:
Rahul Kumar
For modern Java applications, remember that trim() and the newer strip() family have different definitions of whitespace. Use the method that matches your application's requirements.
isEmpty()
The isEmpty() method checks whether a String contains zero characters.
String value = ""; System.out.println(value.isEmpty());
Output:
true
A string containing spaces is not empty because spaces are still characters.
String value = " "; System.out.println(value.isEmpty());
The result is false.
isBlank()
Java also provides isBlank(), which checks whether a string is empty or contains only whitespace characters.
String value = " "; System.out.println(value.isBlank());
Output:
true
This makes isBlank() particularly useful when validating text entered by users.
contains()
The contains() method checks whether a string contains a specified sequence of characters.
String message = "Welcome to Java";
System.out.println(message.contains("Java"));
System.out.println(message.contains("Python"));
Output:
true false
The check is case-sensitive. "Java" and "java" are different sequences.
startsWith()
The startsWith() method checks whether a string begins with a specified prefix.
String url = "https://example.com";
System.out.println(url.startsWith("https"));
System.out.println(url.startsWith("http:"));
This kind of check is useful when processing prefixes such as URL schemes, file names, identifiers, or application-specific codes.
endsWith()
The endsWith() method checks whether a string ends with a specified suffix.
String fileName = "report.pdf";
System.out.println(fileName.endsWith(".pdf"));
System.out.println(fileName.endsWith(".txt"));
Output:
true false
indexOf()
The indexOf() method searches for a character or sequence of characters and returns its first matching index.
String text = "Java Programming";
System.out.println(text.indexOf("Java"));
System.out.println(text.indexOf("Programming"));
System.out.println(text.indexOf("Python"));
If the requested text is not found, indexOf() returns -1.
When using indexOf(), always remember that -1 means the searched value was not found. Never assume that every search produces a valid index.
lastIndexOf()
The lastIndexOf() method searches from the end of the string and returns the index of the last occurrence.
String text = "Java is Java";
System.out.println(text.indexOf("Java"));
System.out.println(text.lastIndexOf("Java"));
This distinction becomes useful when a character or word appears multiple times.
replace()
The replace() method returns a new String in which matching characters or character sequences are replaced.
String message = "Java is difficult";
String result = message.replace("difficult", "interesting");
System.out.println(result);
Output:
Java is interesting
Again, the original String is not modified.
substring()
The substring() method extracts part of a string and returns it as another String.
String language = "Java Programming"; String part = language.substring(5); System.out.println(part);
Output:
Programming
You can also specify both a starting index and an ending index.
String language = "Java Programming"; String part = language.substring(0, 4); System.out.println(part);
Output:
Java
The starting index is inclusive, while the ending index is exclusive. This is an extremely common source of beginner mistakes.
concat()
The concat() method joins one String to the end of another.
String first = "Hello "; String second = "Java"; String result = first.concat(second); System.out.println(result);
Output:
Hello Java
For simple concatenation, the + operator is usually more convenient and readable, but concat() is useful to recognize when reading existing Java code.
equals()
The equals() method compares the contents of two strings.
String first = "Java"; String second = "Java"; System.out.println(first.equals(second));
Output:
true
String comparison deserves its own detailed chapter, so the important point here is simply that equals() checks content rather than whether two variables refer to the same object.
equalsIgnoreCase()
The equalsIgnoreCase() method compares strings without considering differences in letter case.
String first = "Java"; String second = "JAVA"; System.out.println(first.equalsIgnoreCase(second));
Output:
true
This can be useful when a user's input should be treated the same regardless of uppercase or lowercase letters.
compareTo()
The compareTo() method compares two strings lexicographically and returns an integer describing their ordering.
String first = "Apple"; String second = "Banana"; System.out.println(first.compareTo(second));
A negative result means the first string comes before the second according to the comparison rules, zero means they compare equally, and a positive result means the first comes after the second.
Do not rely on the exact positive or negative number unless your application specifically requires it. Usually, you only need to check whether the result is less than, equal to, or greater than zero.
split()
The split() method divides a string into multiple pieces based on a delimiter or regular expression and returns an array.
String languages = "Java,Python,Go";
String[] values = languages.split(",");
for (String value : values) {
System.out.println(value);
}
Output:
Java Python Go
Remember that the argument to split() is treated as a regular expression. Characters with special meaning in regular expressions may need escaping.
join()
The String.join() method combines multiple character sequences using a delimiter.
String result = String.join(" - ", "Java", "Python", "Go");
System.out.println(result);
Output:
Java - Python - Go
This is particularly convenient when a collection or sequence of values needs to be presented as one readable string.
format()
The String.format() method creates formatted text using placeholders.
String name = "Asha";
int score = 95;
String result = String.format("Student: %s, Score: %d", name, score);
System.out.println(result);
Output:
Student: Asha, Score: 95
Formatting is especially useful when constructing readable messages, reports, and logs. Modern Java also provides formatted string features such as formatted() for certain use cases.
toString()
A String already represents text, so calling toString() on a String returns its textual value.
String language = "Java"; System.out.println(language.toString());
Output:
Java
You rarely need to call this method explicitly on a String, but understanding it is useful because toString() is part of the common object behaviour in Java.
Methods Return Values
A useful habit is to ask: “What does this method return?” Many String methods return another String, while others return a number, character, boolean, or array.
| Method | Return Type | Purpose |
|---|---|---|
| length() | int | Returns string length |
| charAt() | char | Returns a character at an index |
| toUpperCase() | String | Returns uppercase text |
| contains() | boolean | Checks whether text exists |
| indexOf() | int | Finds the first matching index |
| substring() | String | Extracts part of a string |
| split() | String[] | Splits text into an array |
| equals() | boolean | Compares string contents |
Common Beginner Mistakes
- Forgetting that String methods return results instead of modifying the original String.
- Using an invalid index with charAt() or substring().
- Assuming contains(), startsWith(), and endsWith() ignore case.
- Forgetting that indexOf() returns -1 when a value is not found.
- Confusing isEmpty() with isBlank().
- Treating the ending index of substring() as inclusive.
- Forgetting that split() accepts a regular expression.
Best Practices
- Choose the method that directly expresses your intention instead of manually implementing the same operation.
- Store returned String values when you need to use the transformed text later.
- Validate indexes before calling index-sensitive methods.
- Use equals() or equalsIgnoreCase() for content comparison.
- Use isBlank() when whitespace-only input should be considered empty.
- Use StringBuilder instead of repeatedly concatenating large amounts of text in performance-sensitive code.
Interview Insight
Interviewers often test String methods through small output-based questions. The most important details to remember are that String methods generally do not mutate the original object, indexes start at zero, substring() uses an exclusive ending index, indexOf() returns -1 when no match exists, and equals() compares content.
String Methods at a Glance
| Method | Main Purpose | Example |
|---|---|---|
| length() | Find length | text.length() |
| charAt() | Read a character | text.charAt(0) |
| toUpperCase() | Convert to uppercase | text.toUpperCase() |
| toLowerCase() | Convert to lowercase | text.toLowerCase() |
| trim() | Remove leading and trailing whitespace | text.trim() |
| isEmpty() | Check for zero characters | text.isEmpty() |
| isBlank() | Check for empty or whitespace-only text | text.isBlank() |
| contains() | Search for text | text.contains("Java") |
| indexOf() | Find first occurrence | text.indexOf("Java") |
| replace() | Replace matching text | text.replace("old", "new") |
| substring() | Extract text | text.substring(0, 4) |
| split() | Divide text into an array | text.split(",") |
| equals() | Compare content | a.equals(b) |
| compareTo() | Compare lexical order | a.compareTo(b) |
Final Takeaway
String methods turn Java's String class into a powerful text-processing toolkit. Methods such as length(), charAt(), contains(), indexOf(), substring(), replace(), and split() cover a large portion of everyday text-processing work. The most valuable habit is to remember that strings are immutable: most operations return a result rather than changing the original String. Once these methods become familiar, you are ready to tackle one of the most frequently tested Java topics—String Comparison.
