Question

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.

Was it helpful?

Solution

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, \u0093) 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 = '\u0027';. Because that is the code point for a single quote, so it gets translated into: char c = ''';.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top