Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem parsing unicode escape in a Java 6 String literal...?

Why does this compile in java 6 (Sun 1.6.0_16):

System.out.println("\u000B");

... but not this:

System.out.println("\u000A");

On this program:

public class Test {
  public static void main(String argv[]) {
  System.out.println("\u000A");
  }
}

I get a

Test.java:3: unclosed string literal
System.out.println("\u000A");

What's going on here?

like image 764
Dafydd Rees Avatar asked Oct 25 '10 08:10

Dafydd Rees


3 Answers

The problem is that the Unicode replacement is done very early in compilation. Unicode escapes aren't just valid in strings and character literals (as other escape sequences such as \t are) - they're valid anywhere in code. They're described in a different area of the spec - section 3.3 rather than section 3.10.6; only the latter is about character and string literal escape sequences.

Basically, read section 3 of the spec for more details on lexical structure :)

So your code was actually equivalent to:

public class Test {
  public static void main(String argv[]) {
  System.out.println("
");
  }
}

... which clearly isn't valid code. For carriage return and line feed, basically it's best to use the "\r" and "\n" escape sequences.

Personally I view this handling of Unicode escaping as a flaw in Java, but there's not a lot we can do about it now :(

like image 55
Jon Skeet Avatar answered Oct 20 '22 06:10

Jon Skeet


Unicode escapes are expanded prior to lexical analysis. The fact that the Unicode escape appears within a string literal is irrelevant. See JLS 3.2.

  • Resource
like image 39
jmj Avatar answered Oct 20 '22 04:10

jmj


it's because \u000a = \n and the compiler process the java source in order to convert it into tokens, so you cannot use that unicode character in your code. The same for \u000d=\r

like image 23
punkers Avatar answered Oct 20 '22 06:10

punkers