简体   繁体   中英

Clarification on Java Language Specification

I read the following phrase in the Java language specification.

It is a compile-time error for the character following the SingleCharacter or EscapeSequence to be other than a '.'

I am not able to understand what is the meaning of above line. Could someone please explain it with example.

What is says is basically: A compile time error will be generated for every character different than a ' , that comes after the "character" itself. Where the "character" is the content in the form of a character (like: a , 0 , ) or an escape sequence (like: \\\\ , \\b , \\n ).

So, this will be wrong:

  • 'aa' , because the second a is not a single quote ( ' ).
  • '\\\\a' , because the second character (the a ) is not a single quote.
  • 'a , because the character which comes after the "content" is not a quote (but probably a newline or a space).

Side note: This won't work either: char c = '\''; . Because that is the code point for a single quote, so it gets translated into: char c = '''; .

I guess this is about character literals. Another way to say this is: character literals must be enclosed by apostrophes, it is an error if you forget the second apostrophe.

Hence:

'a'          // correct
'\007'       // correct
'ab          // wrong

In Java, you can define character variable as an escape sequences or single characters. Those should be surrounded by single quotes.

char ch = 'a'; 
// Unicode for uppercase Greek omega character
char uniChar = '\u039A';

More information and examples can be found in Java tutorial on Characters .

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