Clarification on String Literal based on Java Language Specification

java

Solution

The syntax `"\n"` is a valid, escaped representation of a line terminator, instead of an actual line terminator. The JLS precludes you from doing something like this:

String alphabet = "abcdefghijklm
   nopqrstuvwxyz";

Instead, you have to do:

String alphabet = "abcdefghijklm" +
    "nopqrstuvwxyz";

Problem

It is mentioned in the Java Language specification A string literal is always of type String (§4.3.3). It is a compile-time error for a line terminator to appear after the opening " and before the closing matching ". As specified in §3.4, the characters CR and LF are never an InputCharacter; each is recognized as constituting a LineTerminator. But I can create and run the following statement ``` public class StringOperation { public static void main(String ...args){ String first = "\n"; System.out.println(first); } } ``` and I do not see any error. Thanks for all insight.

Original source