What does "\1" represent in this Java string?
Asked Answered
A

2

26
System.out.println("\1");

I thought it did not compile because of the non-recognized escape sequence.

What does "\1" exactly represent?

Arraign answered 12/7, 2013 at 13:39 Comment(0)
M
23

It's an octal escape sequence, as listed in section 3.10.6 of the JLS. So for example:

String x = "\16";

is equivalent to:

String x = "\u000E";

(As Octal 16 = Hex E.)

So \1 us U+0001, the "start of heading" character.

Octal escape sequences are very rarely used in Java in my experience, and I'd personally avoid them where possible. When I want to specify a character using a numeric escape sequence, I always use \uxxxx.

Mazer answered 12/7, 2013 at 13:41 Comment(8)
Java is one of those languages that make you swear profusely when you hit the "incidental" bugs it has. Did you know that Java interprets character escapes to be a literal character in the source code? Well this isn't a problem until you try and escape a carriage return... then Java thinks you stuck a newline in your source code when you really didn't want one.Diley
@PP.: It depends on which character escape you mean. For example, a comment of // This \n is okay is fine, but // This \u000a is not will not compile.Mazer
Your second code line doesn't compile (on my machine at least): "string literal is not properly closed by a double-quote".Magnus
Also, since Java does not have raw strings, using regular expressions with back references requires the use of \\1, which can be quite irritating.Dominations
I disagree with the value of using \u. This is because Java will interpret \u as starting a a hex escape sequence anywhere in your Java code, including in comments and identifiers. The compiler replaces the character before compiling your code, potentially leading to strange bugs. For example: github.com/antlr/antlr4/issues/164Antiphon
@Kevin: Yes, but I don't use non-ASCII identifiers, and in a comment I'd use U+000D or something similar instead. Neither of those cases is one where "I want to specify a character using a numeric escape sequence".Mazer
That makes sense. I guess I haven't run into situations where I need to specify a non-ASCII character in Java. What I'm more afraid of is accidentally typing \uxxxx in a string like a file path (like the bug I posted), not deliberately using it to specify a special character.Antiphon
@Antiphon Just another reason not to use backslashes in path names. BTW, I guess the octal notation like also the octal int literals are there to make C programmers feel comfortable. Interestingly, octal literals are frowned upon, while hexadecimal ones are fine.Antipersonnel
G
2

In java It is following value

\u0001
Grease answered 12/7, 2013 at 13:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.