7. Translating escape sequences programmatically
We already know that the compiler is responsible for the translation of escape sequences, and most of the time, there is no need to explicitly interfere in this process. But there are cases when we may need programmatic access to this process (for instance, to explicitly un-escape a string before passing it to a function).
Starting with JDK 15, we can accomplish this via String.translateEscapes()
, which is capable of un-escape sequences such as \t
, \n
, \b
, and so on, and octal numbers (\0
–\377
). However, this method doesn’t translate Unicode escapes (\uXXXX
).
We can perform an equality test in order to reveal how translateEscapes()
works:
String newline = "\\n".translateEscapes();
System.out.println(("\n".equals(newline)) ? "yes" : "no");
As you can already intuit, the result is yes.
Next, let’s assume that we want to use an external service that prints...