-2

Metacharacters like ., \, {, ^, |, ] can be escaped with the \ character. But char variables can only store exactly one character. So is it possible to store these special characters in char variables in Java?

Maybe you only need to use the escape character in String variables?

tk421
  • 5,288
  • 6
  • 22
  • 32
Ricky
  • 187
  • 10
  • 1
    "is it possible to store these special characters in char variables" - they're not special characters, they're special character sequences. And `char` doesn't store sequences, it only stores single characters. – Erwin Bolwidt Jul 15 '19 at 22:24
  • 3
    Did you try just `char c = '.';`? – GBlodgett Jul 15 '19 at 22:26
  • What I noticed is in case of a \ character you should do this: `char c = '\\';` Why is that? – Ricky Jul 15 '19 at 22:42
  • these characters, with exception of `'\'` are only special characters in regular expressions; and regular expressions are given as `String` (actually they must not be escaped with backslash - compile error). Here a list (of all) characters that can/must be escaped (as `char` or in `String`): [EscapeSequence](https://docs.oracle.com/javase/specs/jls/se12/html/jls-3.html#jls-EscapeSequence) – user85421 Jul 15 '19 at 22:55

3 Answers3

1

All of the characters in your question can be stored in either a String or a char variable without escaping them except for the escape character \ itself. You only have to escape them if some method that is acting on the string or char may behave differently if it can have a mix of normal characters and those which have special meaning.

String.format() is a good example of where it is likely you might have both. If you want to store the escape char \ in a single character you can do something like this:

char c = '\\'
Tech-ish
  • 11
  • 2
0

Yes, it is possible.

char c = '.'; 

Escaping meta-characters is only when you're dealing with Strings, not chars.

RaminS
  • 2,151
  • 3
  • 19
  • 29
0

it's perfectly possible to store these characters in char variables. Are you using "" quotes instead of ''? It's a common error with char.