591 Escaped Characters in Literals
Fall 2004, David Matuszek
Here is something that may be causing problems in your current assignment.
Suppose you read in the following line from a file:
System.out.println("max = " + max + '\n');
If you read this statement in from a file, you will get exactly the characters
that you see here. For example, you will get
'\n' as four separate
Remember, however, that some characters must be escaped (preceded by a backslash) when included in a String literal or a character literal. Hence, the following does not give you the same string as above:
String s = "System.out.println("max = " + max + '\n');";
In fact, it has syntax errors in it, because of the unescaped quotation marks.
And if you fixed that problem by escaping the quotation marks, the
would be a single (newline) character. To get the same string as you
would read from a file, you have to write it this way:
String s = "System.out.println(\"max = \" + max + '\\n');";
To find out what characters are really in your string, simply print it out. Whatever you print is what's really there.
The single quote (
') does not have to be escaped in a String literal,
but it does as a character literal:
char ch = '\'';
Again, you can check to see what characters you really have just by printing them out.