Java Tutorial

Operators

Flow Control

String

Number and Date

Built-in Classes

Array

Class and Object

Inheritance and Polymorphism

Exception Handling

Collections, Generics and Enumerations

Reflection

Input/Output Stream

Annotation

Replacement Of Java Strings (replace(), ReplaceFirst() And ReplaceAll())

Java strings are immutable, which means that once they are created, their value cannot be changed. However, Java provides several methods to create new strings with modified content. In this tutorial, we will cover three common methods to replace characters or substrings in Java strings: using the replace() method, the replaceFirst() method, and the replaceAll() method.

Method 1: Using the replace() method

The replace() method of the String class can be used to replace all occurrences of a specific character or substring with another character or substring.

Example:

public class Main {
    public static void main(String[] args) {
        String input = "Hello World! This is an example.";
        String output = input.replace("example", "demo");
        System.out.println("Original string: " + input);
        System.out.println("Replaced string: " + output);
    }
}

Method 2: Using the replaceFirst() method

The replaceFirst() method of the String class can be used to replace the first occurrence of a specific substring with another substring. The method takes a regular expression pattern as an argument, so you must escape any characters that have special meaning in regular expressions.

Example:

public class Main {
    public static void main(String[] args) {
        String input = "Hello World! This is an example. Another example.";
        String output = input.replaceFirst("example", "demo");
        System.out.println("Original string: " + input);
        System.out.println("Replaced string: " + output);
    }
}

Method 3: Using the replaceAll() method

The replaceAll() method of the String class can be used to replace all occurrences of a substring with another substring using a regular expression pattern. This method is more powerful than the replace() method, as it allows you to use regular expressions for pattern matching and replacement.

Example:

public class Main {
    public static void main(String[] args) {
        String input = "Hello World! This is an example. Another example.";
        String output = input.replaceAll("ex(ample)", "de$1");
        System.out.println("Original string: " + input);
        System.out.println("Replaced string: " + output);
    }
}

In this example, the regular expression pattern ex(ample) matches the substring "example", and the replacement string de$1 replaces the matched substring with "demo". The $1 in the replacement string refers to the first capturing group in the pattern (the part of the pattern enclosed in parentheses).

In this tutorial, we covered three methods to replace characters or substrings in Java strings. These methods can be used depending on your preference or the specific requirements of your application. Keep in mind that all these methods return a new string with the replaced content, as the original string remains unchanged due to its immutability.

  1. Replacing Characters in Java Strings:

    • Using replace() to replace specific characters in a string.
    String replaced = inputString.replace('a', 'b');
    
  2. Using replaceFirst() in Java Strings:

    • replaceFirst() replaces the first occurrence of a character or substring.
    String replacedFirst = inputString.replaceFirst("a", "b");
    
  3. Java replaceAll() Method Examples:

    • replaceAll() replaces all occurrences using regex or string.
    String replacedAll = inputString.replaceAll("a", "b");
    
  4. Replacing Specific Characters in Java Strings:

    • Replacing specific characters with replace().
    String replacedSpecific = inputString.replace("abc", "123");
    
  5. Replacing Substrings in Java using replace():

    • Using replace() to replace substrings.
    String replacedSubstring = inputString.replace("oldSubstring", "newSubstring");
    
  6. Case-Insensitive Replacement in Java Strings:

    • Performing case-insensitive replacement using regex and replaceAll().
    String replacedIgnoreCase = inputString.replaceAll("(?i)old", "new");
    
  7. Replacing Multiple Occurrences in Java Strings:

    • Replacing multiple occurrences using replace().
    String replacedMultiple = inputString.replace("a", "b");
    
  8. Java Regex in replaceAll() Method:

    • Using regex patterns in replaceAll() for advanced replacements.
    String replacedRegex = inputString.replaceAll("\\d", "");
    
  9. Replacing Newline Characters in Java Strings:

    • Replacing newline characters with a space.
    String replacedNewline = inputString.replace("\n", " ");
    
  10. Replacing Spaces with Underscores in Java:

    • Replacing spaces with underscores using replace().
    String replacedSpaces = inputString.replace(" ", "_");
    
  11. Replace Certain Characters with Escape Sequences in Java:

    • Replacing special characters with escape sequences.
    String replacedEscape = inputString.replace("\t", "\\t");
    
  12. Conditional Replacement in Java Strings:

    • Conditional replacement based on a condition.
    String replacedConditionally = (condition) ? inputString.replace("a", "b") : inputString;
    
  13. Replacing Special Characters in Java Strings:

    • Handling special characters using replace() or replaceAll().
    String replacedSpecial = inputString.replace("@", "_at_");