Search⌘ K
AI Features

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.

Java 25
class ChangeCase {
public static void main(String[] args) {
String role = "SuperAdmin";
String lower = role.toLowerCase();
String upper = role.toUpperCase();
System.out.println("Original: " + role);
System.out.println("Lowercase: " + lower);
System.out.println("Uppercase: " + upper);
}
}
  • Line 3: We define a mixed-case string role.

  • Line 5: .toLowerCase() returns a new string "superadmin", assigned to lower.

  • Line 6: .toUpperCase() returns a new string "SUPERADMIN", assigned to upper.

  • Lines 8–10: We print all three, verifying the original role variable 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.

Java 25
public class StringLength {
public static void main(String[] args) {
String greeting = "Hello, Java!";
String emptyText = "";
int greetingLength = greeting.length();
int emptyLength = emptyText.length();
System.out.println("Greeting length: " + greetingLength);
System.out.println("Empty string length: " + emptyLength);
}
}
  • 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 of greeting and store the result in an integer variable.

  • Line 7: We call .length() on the empty string, which safely evaluates to 0.

  • Lines 9–10: We print the results, which output 12 and 0, 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.

Java 25
public class StringSearch {
public static void main(String[] args) {
String sentence = "Java is fun, and Java is powerful.";
int firstJava = sentence.indexOf("Java");
int lastJava = sentence.lastIndexOf("Java");
int pythonIndex = sentence.indexOf("Python");
System.out.println("First 'Java' at: " + firstJava);
System.out.println("Last 'Java' at: " + lastJava);
System.out.println("'Python' found at: " + pythonIndex);
}
}
  • 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.

Java 25
public class StringExtract {
public static void main(String[] args) {
String email = "support@educative.io";
// Find the index of the '@' symbol
int atIndex = email.indexOf("@");
// Extract everything before '@'
// substring(0, 7) takes characters from index 0 up to (but not including) 7
String username = email.substring(0, atIndex);
System.out.println("Username: " + username);
}
}
  • 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 prefer strip(), though trim() is still widely used.

Java 25
public class StringClean {
public static void main(String[] args) {
String rawInput = " admin ";
// Classic trim (valid, but older style)
String trimmed = rawInput.trim();
// Modern strip (Java 11+ recommended)
String stripped = rawInput.strip();
System.out.println("Original: '" + rawInput + "'");
System.out.println("Trimmed: '" + trimmed + "'");
System.out.println("Stripped: '" + stripped + "'");
}
}
  • 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().

Java 25
public class StringCheck {
public static void main(String[] args) {
String filename = "Report.java";
// Check content
boolean isJavaFile = filename.endsWith(".java");
boolean hasText = !filename.isEmpty();
int length = filename.length();
System.out.println("Is Java File: " + isJavaFile);
System.out.println("Length: " + length);
// Access specific character
char firstLetter = filename.charAt(0);
System.out.println("First letter: " + firstLetter);
}
}
  • Line 6: .endsWith(".java") returns true because the string matches that suffix. We can also use .startsWith() or .contains().

  • Line 7: .isEmpty() returns true only 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.