Java Reference
In-Depth Information
§15.24, “Conditional-Or Operator ||
71. Understand how escape characters are interpreted when strings are
loaded
Many classes allow inclusion of escape sequences in character and string literals.
Examples include java.util.regex.Pattern as well as classes that support XML-
and SQL-based actions by passing string arguments to methods. According to the JLS,
§3.10.6, “Escape Sequences for Character and String Literals” [JLS 2013],
The character and string escape sequences allow for the representation of some non-
graphiccharactersaswellasthesinglequote,doublequote,andbackslashcharacters
in character literals (§3.10.4) and string literals (§3.10.5).
Correct use of escape sequences in string literals requires understanding how the es-
cape sequences are interpreted by the Java compiler, as well as how they are interpreted
by any subsequent processor, such as an SQL engine. SQL statements may require escape
sequences (for example, sequences containing \t , \n , \r ) in certain cases, such as when
storing raw text in a database. When representing SQL statements in Java string literals,
each escape sequence must be preceded by an extra backslash for correct interpretation.
As another example, consider the Pattern class used in performing regular
expression-related tasks. A string literal used for pattern matching is compiled into an in-
stance of the Pattern type. When the pattern to be matched contains a sequence of char-
actersidenticaltooneoftheJavaescapesequences— "\" and "n" ,forexample—theJava
compiler treats that portion of the string as a Java escape sequence and transforms the se-
quence into an actual newline character. To insert a newline escape sequence, rather than
a literal newline character, the programmer must precede the "\n" sequence with an addi-
tional backslash to prevent the Java compiler from replacing it with a newline character.
The string constructed from the resulting sequence,
\\n
consequently contains the correct two-character sequence \n andcorrectly denotes the es-
cape sequence for newline in the pattern.
In general, for a particular escape character of the form \X , the equivalent Java repres-
entation is
\\X
Search WWH ::




Custom Search