Strings Operations
Explore fundamental Java string operations to manipulate and process textual data accurately. Understand methods for changing case, searching, extracting substrings, trimming whitespace, and checking string content, enabling cleaner data handling and improved application input processing.
Once we know how to create and compare strings, we need to know how to manipulate them. Real-world data is rarely perfectly formatted. Users add accidental spaces to form inputs, system logs embed values within long text lines, and search features require case-insensitive matching. Java provides a rich API for extracting, cleaning, and inspecting text. We will explore the most essential methods for transforming string data into exactly what our applications need.
Changing case
Text comparisons are often case-sensitive in Java. "admin" and "Admin" are completely different strings. To normalize text for comparisons or display, we use .toLowerCase() and .toUpperCase().
Remember that strings are immutable. These methods do not alter the existing string; they return a brand new string with the casing changed.
Line 3: We define a mixed-case string
role.Line 5:
.toLowerCase()returns a new string"superadmin", assigned tolower.Line 6:
.toUpperCase()returns a new string"SUPERADMIN", assigned toupper.Lines 8–10: We print all three, verifying the original
rolevariable remains entirely unchanged.
Finding the length of a string
Before extracting or processing text, we often need to know its exact length. We can determine the total number of characters in a string using the .length() method. The .length() method counts every single character in the sequence, including spaces, numbers, and punctuation marks.
Line 3: We define a string containing 12 characters (the letters, plus the comma, space, and exclamation mark).
Line 4: We define a completely empty string, containing zero characters.
Line 6: We call
.length()to calculate the size ofgreetingand store the result in an integer variable.Line 7: We call
.length()on the empty string, which safely evaluates to0.Lines 9–10: We print the results, which output
12and0, respectively.
Searching for text
We search for text using indexOf() (finds the first occurrence) and lastIndexOf() (finds the last occurrence). These return -1 if the text is not found.
Line 5: Finds the first
"Java"starting at index 0.Line 6: Finds the last
"Java"starting at index 17.Line 7: Searches for
"Python". Since it is not in the string, it returns-1.
Extracting text
We often need to extract a portion of a larger string. We use substring(int beginIndex, int endIndex).
beginIndex: The starting position (inclusive).endIndex: The ending position (exclusive).
Indices in Java are zero-based. In the string "Java", ‘J’ is at index 0, ‘a’ at 1, ‘v’ at 2, and ‘a’ at 3.
Line 6:
indexOf("@")scans the string and returns the integer index of the first@symbol (which is 7).Line 10:
substring(0, atIndex)grabs characters starting at index 0 up to index 7. The character at index 7 (‘@’) is not included.Line 12: The output is: support.
Cleaning input
When dealing with user input, we often get accidental spaces at the start or end of a string (e.g., " user "). Java provides methods to remove this whitespace cleanly.
trim(): The classic method. It removes ASCII whitespace (spaces, tabs, newlines) from both ends.strip(): The modern (Java 11+) method. It is “Unicode-aware,” meaning it removes all types of whitespace, including special invisible characters from other languages. In modern Java, we preferstrip(), thoughtrim()is still widely used.
Line 3: The string contains two spaces before and two spaces after "admin".
Line 6:
trim()creates a new string with surrounding spaces removed. It is sufficient for standard English text.Line 9:
strip()does the same but is smarter about Unicode whitespace (like non-breaking spaces).Lines 11–13: Both methods result in the clean string
"admin", verifying the spaces are gone.
Checking content and accessing characters
We can inspect strings to see if they contain specific patterns or are empty. We can also grab individual characters using charAt().
Line 6:
.endsWith(".java")returnstruebecause the string matches that suffix. We can also use.startsWith()or.contains().Line 7:
.isEmpty()returnstrueonly if the string length is 0. We negate it with!to ensure text exists.Line 8:
.length()returns the total count of characters (11).Line 14:
.charAt(0)retrieves the character at index 0 (‘R’).
We now have a comprehensive toolkit for manipulating text. We can combine data using concatenation and formatting, sanitize messy inputs with .strip(), normalize data with case transformations, and extract exactly what we need using .indexOf() and .substring(). These operations form the foundation of text parsing in Java.