Java String.translateEscapes
Interpret Java escape sequences stored as literal characters in a string.
A simple example
String.translateEscapes
- Start with A, backslash, n, B
- Do this Interpret the escape
- Result A and B on two lines
class Main {
public static void main(String[] args) throws Exception {
System.out.println("A\\nB".translateEscapes());
}
}
A B
Syntax
public String translateEscapes()
JDK 21 method signatures (1)
public String translateEscapes()Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaRead two rows from a saved print template
A saved template contains escape markers that represent formatting instructions. Decode the stored markers once so the printed timetable has real tabs or line breaks at the intended positions.
class Main {
public static void main(String[] args) throws Exception {
String saved = "Tea\\nRice";
System.out.println(saved.translateEscapes().lines().count());
}
}
2
The literal backslash and n in the saved template become one line break.
Decode a tab marker in a timetable
A timetable template saves a marker between two columns rather than storing a real tab. Interpret the marker once so the renderer sees a column separator when preparing the final timetable.
class Main {
public static void main(String[] args) throws Exception {
String saved = "09:00\\tMath";
System.out.println(saved.translateEscapes().replace("\t", " | "));
}
}
09:00 | Math
The escape becomes a tab which the display replaces with a visible column divider.
Decode an address template
A mailroom stores the street and town in a one-line template. The stored template contains the two printable characters backslash and n. After decoding them as a newline, how many lines does the printer see?
What to watch for
This is Java escape syntax. Invalid escapes raise IllegalArgumentException and backslash-u Unicode escapes are not translated by this method.