Reputation: 591
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?
Upvotes: 0
Views: 831
Reputation: 159165
Because the octal escape sequence can only specify 1-byte character values and octal 777
is decimal 511
, i.e. 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
\u0000
through\u00FF
, 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
.
Upvotes: 2
Reputation: 178313
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.
Upvotes: 2
Reputation: 8626
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);
}
}
Upvotes: 1