0

Possible Duplicate:
‘ \ ’-Invalid character constant?

In Java, I am trying to initialize a char variable like below, which it is not allowing.

char ch = '\';

Any reason behind this? It's giving a compilation error.

Community
  • 1
  • 1
NPKR
  • 5,368
  • 4
  • 31
  • 48
  • you need to escape the backslash. '\\' – Rahul Dec 28 '12 at 12:11
  • refer http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html Also http://stackoverflow.com/questions/5859934/char-initial-value-in-java – Rajshri Dec 28 '12 at 12:16

2 Answers2

5

you need to escape it:

char backslash = '\\';
char quotation = '\'';

The reason is, this \' is a single quotation mark.

System.out.println(backslash); // prints \
System.out.println(quotation); // prints '
jlordo
  • 37,490
  • 6
  • 58
  • 83
1

Characters like \, " and ' hold special meaning. Therefore to use them as character literals, you need to escape them. They need to be written as '\\', '\'' and '\"' respectively.
e.g. char c = '\\';

Similarly, to include them in strings, you need to escape them.
e.g. String path = "C:\\Program Files\\Java"

bane
  • 811
  • 1
  • 8
  • 23