top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Replace in Java

Overview

A char array in Java internally supports objects known as strings. A string is a type of exceptional array. Arrays are unchangeable, and strings share this feature. Strings can also accommodate characters like arrays do. You can execute various operations on strings, like compare(),  split(), replace(), equals(), etc. 

Java String replace()

This tutorial focuses on the Java string.replace() method, where a new one can replace every occurrence of the old character. This method returns a string to replace each old character with a new char or CharSequence.

Since the launch of JDK 1.5, a new operation has been introduced in Java that allows you to replace an entire sequence of char values.

Exceptions under the Replace() Method

The replace() method has a specific feature where a null regular expression does not get accepted, this scenario is known as the NullPointerException.

Applications of the Java.String.replace() Operation 

Java replace regex allows you to replace characters with a regular expression. The Java replace() method has several other functionalities, such as:

  • Assists in reading data from files with comma-separated values, where you can replace the delimiters with a space using this method to split the words.

  • Allows you to change and replace special characters for specific demands, like language and dialect. These replacements do not change the ulterior meaning of the word, it simply makes the string more understandable across the world. 

  • Helps with handling URLs in Java, where you can encode the string to replace the desired characters. 

replace() Syntax

The replace() method in Java has two different overloads:

  1. replace(char oldChar, char newChar): This overload replaces all occurrences of the oldChar character with the newChar character in the string. The method returns a new string with the replacements.

Example Syntax:

String originalString = "Hello!";
String replacedString = originalString.replace('o', 'e');
System.out.println(replacedString); // Output: Helle!

In this example, the replace('o', 'e') call replaces all occurrences of the character 'o' with the character 'e' in the original string "Hello!", resulting in the replaced string "Helle!".

  1. replace(CharSequence target, CharSequence replacement): This overload replaces all occurrences of the target sequence with the replacement sequence in the string. The target and replacement parameters can be either a String or a StringBuilder object. The method returns a new string with the replacements.

Example Syntax:

String originalString = "Hello!";
String replacedString = originalString.replace("Hello", "Hi");
System.out.println(replacedString); // Output: Hi!

In this example, the replace("Hello", "Hi") call replaces all occurrences of the substring "Hello" with the substring "Hi" in the original string "Hello!", resulting in the replaced string "Hi!".

replace() Return Value

The return value of the replace() method is a new string object that represents the original string with the modifications or replacements made. It does not modify the original string itself because strings in Java are immutable. Instead, the replace() method creates and returns a new string that reflects the modifications.

public class upGrad {
    public static void main(String[] args) {
        String originalString = "upGras";
        String replacedString = originalString.replace('s', 'd');

        System.out.println(originalString);  // Output: upGras
        System.out.println(replacedString);  // Output: upGrad
    }
}

In this example, the replace() method is called on the originalString object. The return value of the method is assigned to the replacedString variable. Notice that the originalString remains unchanged, while the replacedString contains the modified string with the replacements applied.

It's important to store and use the return value of the replace() method if you want to work with the modified string.

String replaceFirst()

Similar to the Java.String.replace() method, this technique replaces the first substring of the string that has a match between the provided regular expression and the given replacement value. 

Identical to the Java.String.replace() operation, this method also returns a resulting string. 

Examples of String replace()

public class upGrad {
    public static void main(String[] args) {
        // Example 1: Replacing a single character
        String originalString1 = "upGrad";
        String replacedString1 = originalString1.replace('u', 'U');
        System.out.println("Example 1:");
        System.out.println("Original string: " + originalString1);
        System.out.println("Replaced string: " + replacedString1);
        System.out.println();

        // Example 2: Replacing a substring
        String originalString2 = "upGrad";
        String replacedString2 = originalString2.replace("Grad", "Skills");
        System.out.println("Example 2:");
        System.out.println("Original string: " + originalString2);
        System.out.println("Replaced string: " + replacedString2);
        System.out.println();

        // Example 3: Replacing multiple characters
        String originalString3 = "upGrad";
        String replacedString3 = originalString3.replace("u", "U").replace("p", "P");
        System.out.println("Example 3:");
        System.out.println("Original string: " + originalString3);
        System.out.println("Replaced string: " + replacedString3);
        System.out.println();

        // Example 4: Replacing multiple characters using regex
        String originalString4 = "upGrad";
        String replacedString4 = originalString4.replaceAll("[aeiou]", "*");
        System.out.println("Example 4:");
        System.out.println("Original string: " + originalString4);
        System.out.println("Replaced string: " + replacedString4);
    }
}

Output:

The above program demonstrates various examples of using Java's replace() method to replace characters or substrings within a string. Let's go through each example in detail:

Example 1: Replacing a single character

In this example, the original string upGrad is assigned to the originalString1 variable. The replace() method is then used to replace the character 'u' with 'U', resulting in the modified string UpGrad. The original and replaced strings are printed using System.out.println().

Example 2: Replacing a substring

In this example, the original string upGrad is assigned to the originalString2 variable. The replace() method is used to replace the substring "Grad" with "Skills", resulting in the modified string upSkills. Like the previous example, original and replaced strings are printed using System.out.println().

Example 3: Replacing multiple characters

In this example, the original string upGrad is assigned to the originalString3 variable. Chaining multiple replace() methods is applied to replace the characters 'u' and 'p' with their uppercase counterparts, resulting in the modified string UpGrad. The original and replaced strings are then printed using System.out.println().

Example 4: Replacing multiple characters using regex

In this example, the original string upGrad is assigned to the originalString4 variable. The replaceAll() method is used with a regular expression [aeiou] to match and replace all vowels with an asterisk (*), resulting in the modified string *pGr*d. Finally, the original and replaced strings are printed using System.out.println().

replaceFirst() Method

public class upGrad {
    public static void main(String[] args) {
      // Replacing the first occurrence of a substring
        String originalString5 = "upGrad";
        String replacedString5 = originalString5.replaceFirst("a", "A");
        System.out.println("replaceFirst Example:");
        System.out.println("Original string: " + originalString5);
        System.out.println("Replaced string: " + replacedString5);
    }
}

This program begins by defining a class named upGrad. Inside the main method, a string variable originalString5 is declared and assigned the value "upGrad". This variable represents the original string on which the replacement operation will be performed.

The replaceFirst() method is then used on originalString5 to replace the first occurrence of the substring "a" with the character "A". The resulting replaced string is stored in the variable replacedString5.

Finally, to display the output, the program uses System.out.println() to print the heading "replaceFirst Example:". It then prints the original and replaced strings by concatenating them with appropriate messages.

Exceptions with replace() method

The replace() method in Java does not throw any exceptions on its own. It is a safe operation that performs string replacement without raising any exceptions. Therefore, we do not need to handle specific exceptions using the replace() method.

However, it is important to note that the replace() method creates a new string with the replaced characters and returns it. The original string remains unchanged. So if we wish to store the result of the replace() operation, we must assign it to a variable or use it in some way. 

Here is an example:

In the above example, the replace() method is used to replace the substring "World" with "upGrad". The original string remains unchanged, and the replaced string is stored in the replacedString variable.

Code:

public class upGrad {
    public static void main(String[] args) {
        String originalString = "Hello, World!";
        String replacedString = originalString.replace("World", "upGrad");


        System.out.println("Original string: " + originalString);
        System.out.println("Replaced string: " + replacedString);
    }
}

Conclusion

There are three methods of replacing a character in String Class Java, namely:

  • replace()

  • replaceAll()

  • replaceFirst()

This tutorial discussed changing characters in Java using the replace() method. You can improve your knowledge of different Java concepts by checking out similar tutorials. If you are keenly interested in joining an educational journey on Java, you can go through the courses available on upGrad that will assist you in refining your Java skills. 

FAQs 

1. What is the Difference between Replace() and ReplaceAll()?

The replaceAll() function replaces all the instances of a given substring's occurrence with any desired value. On the other hand, replace() is applicable for replacing a selective number of characters with a new value. The replace() function can only replace a specific quantity or 'n' occurrences of a substring, while replaceAll() changes every occurrence of the characters. 

2. How to replace an object in Java?

You can directly replace an object using the replace() method by creating an object that belongs to the string class. The replace() method uses the original string object as an input parameter, followed by returning the new string object. This is the best technique to replace string in Java.

3. How do you remove a letter from a string in Java?

The String class doesn't allow the remove() method to remove letters from a string in Java. You can instead use any variation of the replace() method and the substring() method to remove characters from strings. Knowledge of this method can help work on Java string replace at index with a specified parameter. 

Leave a Reply

Your email address will not be published. Required fields are marked *