Programming

10 Java String Methods You Need to Know

Master Java with the 10 most-used String methods. Learn to manipulate text efficiently and level up your programming skills now!

  10 min

Strings are an essential part of practically any codebase. That’s why it matters for a programming language to provide robust support for manipulating them. Given the importance of this task, this article aims to clearly walk through the ten most important methods for manipulating Strings in Java. Let’s dive in!

1. indexOf()

Used to find characters and substrings within a string. It returns the index of the first occurrence of the substring passed as a parameter within this string; additionally, if we supply a fromIndex, it starts searching from the given index.

indexOf() Syntax

public int indexOf(int str, int fromIndex)

Parameter(s)

  • str: Substring to search for
  • fromIndex: The search starts from this index

Return Value

  • Index of the first occurrence of the specified substring;
  • 0 if an empty string is passed, or;
  • -1 if there is no such occurrence.

Overloaded variants

public int indexOf(int ch)

public int indexOf(int ch, int fromIndex)

public int indexOf(String str)

public int indexOf(String str,int fromIndex)

Practical use of indexOf()

Ever wondered how the search feature in your favorite code editor works?

The indexOf() method can be used to implement that functionality. How?

The approach consists of iterating over every line and using indexOf() with the target string. If there are multiple occurrences of the target string on the same line, the process continues from the point where the last found substring ended.

public static int findOccurrences(String[] paragraph, String target) {
    int totalOccurrences = 0;
    int index = 0;

    for (int lineNumber = 0; lineNumber < paragraph.length; ++lineNumber) {
        String line = paragraph[lineNumber];
        index = line.indexOf(target, index);

        while (index != -1) {
            System.out.println("Found on line " + lineNumber + " at position " + index);
            index += target.length();
            totalOccurrences++;
            index = line.indexOf(target, index);
        }
    }

    return totalOccurrences;
}

In this example, the findOccurrences function scans an array of strings representing a paragraph. It looks for occurrences of the target string and, when found, prints the line and position where the occurrence was located. The index is then updated to continue the search from the next character after the found occurrence. The function returns the total number of occurrences found.

2. toCharArray()

The toCharArray() method is used to create a new character array from a string. The contents of this new array are initialized with the characters present in the original string, and its length equals the string’s length.

toCharArray() Syntax

public char[] toCharArray()

Parameter(s)

None

Return Value

A character array is allocated in memory, containing the characters of the original string, and a reference to that array is returned.

Practical use of toCharArray()

During intensive string manipulation operations, new string objects are frequently created, which can be inefficient in terms of memory usage. An effective strategy is to convert the string to a character array first, perform the needed manipulation operations, and then convert the character array back to a string.

Let’s look at an example where we check whether a given string is a palindrome:

String palindrome = "Dot saw I was Tod";
char[] charArray = palindrome.toCharArray();
int len = charArray.length;
boolean isPalindrome = true;

for (int i = 0, j = len - 1; i < j; i++, j--) {
    if (charArray[i] != charArray[j]) {
        isPalindrome = false;
        break;
    }
}

if (isPalindrome) {
    System.out.println("It's a palindrome");
} else {
    System.out.println("It's not a palindrome");
}

3. charAt()

The charAt() method lets you extract the character at the specified index of the string. This method is useful when you want to check the value of a character at a specific index without having to scan the whole string.

charAt() Syntax

public char charAt(int index)

Parameter(s)

  • Index: index of the character in the string to retrieve

Return Value

char value of the String at the index passed as argument

  • Throws

IndexOutOfBoundsException - if the supplied argument is negative or greater than the length of the String.

Practical use of charAt()

The charAt() method can be used, for example, to iterate over a string and count the frequency of a particular character.

String sentence = "I am improving my skills by learning through doing";
char targetChar = 'a';
int charCount = 0;

for (int i = 0; i < sentence.length(); i++) {
    if (sentence.charAt(i) == targetChar) {
        charCount++;
    }
}

System.out.println("The frequency of character '" + targetChar + "' is: " + charCount);

In this example, the charAt() method is used to scan the string and count how many times the character ‘a’ appears in it. The result is printed to show the frequency of that character in the string.

4. concat()

The given string is appended to the end of the specified string.

concat() Syntax

public String concat(String str)

Parameter(s)

str: string to be appended to the end of a given string

Return Value

A new String object with the concatenation of the passed string at the end of the given string.

Practical use of concat()

Here’s an example using the concat() method to build a personalized welcome message.

import java.util.Scanner;

public class WelcomeMessage {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = scanner.nextLine();

        String greeting = "Hello, ";
        String message = "Welcome to our system!";

        // Using concat() to join the strings
        String personalizedMessage = greeting.concat(name).concat(". ").concat(message);

        System.out.println(personalizedMessage);

        scanner.close();
    }
}

5. replace()

Used to replace characters and substrings in a string.

replace() Syntax

public String replace(char oldChar, char newChar)

Parameter(s)

  • oldChar: Character to be replaced
  • newChar: Character that will replace oldChar

Return Value

A new String object with a string built by replacing all occurrences of oldChar with newChar.

Practical use of replace()

Here’s an example using the replace() method to sanitize a text by removing sensitive words.

import java.util.Scanner;

public class CensorText {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a text: ");
        String originalText = scanner.nextLine();

        String[] bannedWords = {"violent", "offensive", "inappropriate"};
        String censoredText = originalText;

        // Using replace() to substitute banned words
        for (String word : bannedWords) {
            censoredText = censoredText.replace(word, "[CENSORED]");
        }

        System.out.println("Censored text: " + censoredText);

        scanner.close();
    }
}

6. substring()

Used to extract a portion of a string from a given string. It creates a new string object without altering the original string.

substring() Syntax

public String substring(int beginIndex, int endIndex)

Parameter(s)

  • beginIndex: The search starts from this index
  • endIndex: The search ends at endIndex-1

Return Value

A new string object resulting from the part of the original string sliced based on the begin and endIndex indices.

  • Exception:

IndexOutOfBoundsException - if beginIndex is negative or greater than the length of this String object.

Overloaded variant

  1. public String substring(int beginIndex)

Practical use of substring()

It’s possible to identify all substrings within a specific string using the substring() method. Although this isn’t the most optimized approach, it will give you an understanding of how the substring method works.

Here’s an implementation of the SubString method:

public void subString(String str, int n) {
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j <= n; j++) {
            System.out.println(str.substring(i, j));
        }
    }
}

This implementation walks through the original string, generating all possible substrings from consecutive indices. While it works, note that it may not be efficient for very long strings due to the increasing number of iterations.

7. split()

The split() method is used to break the specified string into segments based on a regular expression. Declaring a limit can be used to control the number of resulting strings after the split.

split() Syntax

public String[] split(String regex, int limit)

Parameter(s)

  • regex: Substring to search for.
  • limit: The search starts from this index.

Return Value

An array containing each substring of this string, terminated either by another substring matching the given expression or by the end of the string. The substrings in the array are arranged in the order in which they appear in the original string.

  • Exception

PatternSyntaxException - if the regular expression’s syntax is invalid.

Overloaded variant

  1. public String[] split(String regex)

Practical use of split()

We can count the number of words in a paragraph by splitting the string using a space as the delimiter.

Example:

String str = "This string contains five words";
String[] arrayOfWords = str.split(" ");
System.out.println(arrayOfWords.length);

This snippet splits the string into individual words, represented as elements in an array. The result is the number of words in the original string.

8. compareTo()

As Java programmers, we frequently find the need to sort elements in a list or a class. The compareTo() method is used to compare two strings alphabetically.

compareTo() Syntax

public int compareTo(String anotherString)

Parameter(s)

  • anotherString: The string to compare with.

Return Value

  • Returns 0 if the argument string is equal to the given string.
  • Returns a value < 0 if the given string is lexicographically less than the argument string.
  • Returns a value > 0 if the given string is lexicographically greater than the argument string.

Practical use of compareTo()

Comparison-based sorting algorithms are widely used in many contexts.

In educational institutions, it’s common to sort students by ascending order of their first names. If two students share the same first name, the sort order is then determined by ascending order of their last names.

class Student implements Comparable<Student> {
    String firstName;
    String lastName;

    // Constructor and methods here

    public int compareTo(Student student) {
        int comparison = firstName.compareTo(student.firstName);
        if (comparison == 0) {
            return lastName.compareTo(student.lastName);
        }
        return comparison;
    }
}

public class SortStudents {
    List<Student> students = new ArrayList<Student>();

    // Add students to the list

    Collections.sort(students);
}

In this example, the Student class implements the Comparable interface to allow comparison and sorting based on the specified criteria. The list of students can then be sorted using Collections.sort().

9. strip()

The strip() method is used to remove any whitespace at the beginning and end of the specified string.

strip() Syntax

public String strip()

Parameter(s)

None

Return Value

Returns a new string representing the contents of this original string, but without leading and trailing whitespace.

Practical use of strip()

When we receive input from the presentation layer, it’s crucial to ensure that whitespace at the beginning and end of the string doesn’t affect the actual data. This ensures data is stored consistently in the database and processed correctly on the backend.

The strip() method can also be used to make sure our inputs are free of any contamination.

public static void performLogin() {
    String username = getUsernameFromUI(); // "  user123 "
    String cleanPassword = password.strip(); // "abc"

    Account account = new Account(username.strip(), cleanPassword);

    database.save(account);
}

In this example, the performLogin() function shows how to use the strip() method to remove unnecessary whitespace from inputs, ensuring the integrity of the data handled and stored.

10. valueOf()

The valueOf() method is used to obtain the string representation of the passed argument. valueOf() has several overloaded variants that make it easy to convert almost any primitive type to a string.

valueOf() Syntax

public static String valueOf(char[] data)

Parameter(s)

  • data: Character array to be converted into a string.

Return Value

Returns a new String object containing the data from the array as a string representation of the passed argument.

Overloaded variants

public static String valueOf(boolean b)
public static String valueOf(char c)
public static String valueOf(int i)
public static String valueOf(long l)
public static String valueOf(float f)
public static String valueOf(double d)
public static String valueOf(char[] data)
public static String valueOf(char[] data, int offset, int count)
public static String valueOf(Object obj)

Practical use of valueOf()

It’s possible to form a single sequence by combining all the elements of a character array using the valueOf() method.

Example:

char[] characterArray = { 'a', 'b', 'c', 'd', 'e', 'f', 'g' };
String combinedSequence = String.valueOf(characterArray);

In this example, the combinedSequence variable will hold the string “abcdefg”, formed by concatenating the characters in the characterArray array. The valueOf() method is a handy tool for converting various data types into string representations.

Recap

Here’s a quick summary of the Java string methods we covered in this article.

Java MethodUse
indexOf ()To find the index of the first occurrence of a character or a string in the given string.
toCharArray ()To form a new character array from this string
charAt ()To get the character at the specified index
concat ()To append the given string to the end of the specified string.
replace ()To replace all occurrences of the given character/String with the given String
substring ()To get a portion of a string from the given string.
split ()To split the given string based on the given regular expression.
compareTo ()To compare two Strings lexicographically.
strip ()To remove all trailing and leading whitespace from the given string.
valueOf ()To return the string representation of the passed argument.

List of other useful string methods for further learning

  • contains(CharSequence s)
  • isEmpty()
  • join()
  • repeat()
  • startsWith() / endsWith()
  • toLowerCase() / toUpperCase()
  • indent()

Conclusion

Strings are fundamental to programming, and Java offers a robust String class with powerful methods for manipulating them. By understanding these tools, developers can build more efficient and reliable applications.

Citations

Share:
Back to Blog