Java Replace String With Escape Character

Java Replace String With Escape Character | On this page, we will discuss how to replace the string with the escape character. Prerequisite:- Escape Sequence In Java

In Java programming language ‘/’ backslash is termed to be an escape character. When backslash succeeding with any other character gives a different meaning. For example, ‘\t’ this backslash ‘t’ is meant for a tab space so whenever we use this the compiler gives a tab space. Similarly ‘\n’ gives a line space that is the compiler moves the cursor to the next line.

Example demonstrating backslash with special meaning:-

String str = “Java Programming\n language”;
System.out.println(str);

Resultant:-
Java Programming
language

The string after the ‘\n’ moves to the next line.

String str = "Java Programming\t language";
System.out.println(str);

Resultant:- Java Programming language
The string after ‘\t’ has been moved by tab space.

Test case: Scenario where the code gives an error while replacing backslash.

public class Main {
   public static void main(String[] args) {
      String str = "Java.Programming.Language";
      System.out.println(str.replace('.', '\')); // error
   }
}

Output:-

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Invalid character constant at Main.main(Main.java:4)

The above code gives a compile-time error because we have used backslash ‘\’ this is an escape character by default hence to overcome this use double backslash.  See the below code for proper code.

Java Replace String With Escape Character dot (.)

Java Program To Replace (.) dot by a ‘\’

public class Main {
   public static void main(String[] args) {
      String str = "Java.Programming.Language";
      System.out.println(str.replace('.', '\\'));
   }
}

Output:-

Java\Programming\Language

Using a single quote (‘) within quotes might give an error. Example:-

public class Main {
   public static void main(String[] args) {
      String str = "Java.Programming.Language";
      System.out.println(str.replace('.', ''')); // error
   }
}

Output:-

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Invalid character constant
at Bell1.main(Bell1.java:4)

Hence to overcome this use backslash with the single quote, as backslash is an escape character it escapes the preceding character and helps us to print the single quote (‘). 

Java Replace String with Escape character Single Quote

Java Program To Replace dot (‘.’) with a single quote (‘)

public class Main {
   public static void main(String[] args) {
      String str = "Java.Programming.Language";
      System.out.println(str.replace('.', '\''));
   }
}

Output:-

Java’Programming’Language

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published.