简体   繁体   中英

Escape sequence octal notation not working as expected

class A {
    public static void main(String args[]) {
        char c= '\777';
        System.out.println(c);
    }
}

This is giving compile error (running on Java 8 compiler).

octal notation for escape sequence is of the format '\\xxx' but in the above case its not working, char c='\\077' is working.

What can be the reason for this?

The JLS, Section 3.10.6 , "Escape Sequences for Character and String Literals", states that an octal char literal can be up to 3 octal digits, and if there are 3, then the first one is limited to 0-3.

 OctalEscape: \\ OctalDigit \\ OctalDigit OctalDigit \\ ZeroToThree OctalDigit OctalDigit OctalDigit: (one of) 0 1 2 3 4 5 6 7 ZeroToThree: (one of) 0 1 2 3 

The max \\377 is 255 in decimal, so it looks like this is done so that the value fits in one (unsigned) byte.

Because the octal escape sequence can only specify 1-byte character values and octal 777 is decimal 511 , ie outside the range of a 1-byte value.

As the Java Language Specification 3.10.6. Escape Sequences for Character and String Literals says it:

Octal escapes are provided for compatibility with C , but can express only Unicode values \ through \ÿ , so Unicode escapes are usually preferred .

The full specification of an octal escape is:

 OctalEscape: \\ OctalDigit \\ OctalDigit OctalDigit \\ ZeroToThree OctalDigit OctalDigit OctalDigit: (one of) 0 1 2 3 4 5 6 7 ZeroToThree: (one of) 0 1 2 3 

As you can see, the max allowed octal number is 377 .

Octal characters can go from 0 to 377 (that is in Hex: 0x00 to 0xFF ).

In order to go beyond that, you will need to use the \\uXXXX notation which represents the hexadecimal based in Unicode.

The Java documentation regarding Character is pretty lengthy and offers a lot of information regarding this subject.

For your particular example, I think you want to do something like:

public  class A {
    public static void main(String args[]) {
        char c= '\u0777';
        System.out.println(c);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM