Java - String translateEscapes() Method



The Java String translateEscapes() method retrieves a new string which translates the escape characters (such as \n, \t, \', \", and \\) into a string literal.

A string literal is a reference to a String class instance which contains zero or more characters enclosed in double quotations. Additionally, a string literal is also a constant, meaning that it always refers to the same instance of the String class.

Note − Unicode escapes like "\u2022" are not translated by this method. Unicode escapes are not part of the string literal standard but are instead translated by the Java compiler when it reads input characters.

Syntax

Following is the syntax for Java String translateEscapes() method −

public String translateEscapes()

Parameters

This method does not accept any parameter.

Return Value

This method returns a new String with escape characters translated.

Example

The following example shows the usage of Java String translateEscapes() method. Here we are using the escape character '\n' in a string and calling this method on it −

public class StringDemo {
   public static void main(String[] args) {
      String s = "Welcome \n to \n tutorials \n point";
      System.out.println(s.translateEscapes());
   }
}

Output

If you compile and run the above program, it will produce the following result −

Welcome
 to
 tutorials
 point

Example

Below is an example where '\s' is used as the escape character which helps to return the result with a space in the given string −

public class StringDemo {
   public static void main(String[] args) {
      String s = "Welcome \s to \s tutorials \s point";
      String x = s.translateEscapes();
      System.out.println("The new string is:" + x);
   }
}

Output

If you compile and run the program above, the output will be displayed as follows −

The new string is:Welcome   to   tutorials   point

Example

Now, let us use double quotes(") as an escape character in a string and ivoke this method on it −

public class StringDemo {
   public static void main(String[] args) {
      String s = "\"Welcome \" to \" tutorials \" point\"";
      String res = s.translateEscapes();
      System.out.println("The new string is:" + res);
   }
}

Output

On executing the program above, the output is obtained as follows −

The new string is:"Welcome " to " tutorials " point"
java_lang_string.htm
Advertisements