Escape characters (also called escape sequences or escape codes) in general are used to signal an alternative interpretation of a series of characters. In Java, a character preceded by a backslash (\) is an escape sequence and has special meaning to the java compiler.
When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence: She said "Hello!" to me. you should write:
System.out.println("She said \"Hello!\" to me.");
Escape sequences available in java are:
\t - Insert a tab in the text at this point.
\b - Insert a backspace in the text at this point.
\n - Insert a newline in the text at this point.
\r - Insert a carriage return in the text at this point.
\f - Insert a formfeed in the text at this point.
\' - Insert a single quote character in the text at this point.
\" - Insert a double quote character in the text at this point.
\\ - Insert a backslash character in the text at this point.
An escape sequence is a single character. For example
System.out.println("\n".length()); will print 1.
Question 1: What will System.out.println("\".length()); give?
Question 2: What will System.out.println("a\".length() + \"b".length()); print?
Question 3: If \u0022 is the Unicode escape for double quote ("), then what will the below line print:
It will give a compilation error because \" is taken as an escape sequence character and hence the string literal needs another double quotes to be properly closed.
Answer is 16. Here \" that comes before .length and b are escape sequences. Hence the string literal whose length we are finding out is a\".length() + \"b . Also \" is a single character. Therefore length of a\".length() + \"b is 16.
System.out.println("a\u0022.length() + \u0022b".length());
It will print 2. Java provides no special treatment for Unicode escapes within string literals.
Explanation: The compiler translates Unicode escapes into the characters they represent before it parses the program into tokens, such as strings literals. You can use escape sequences in character literals as well as in string literals. You can actually put any ASCII character into a string literal or a character literal by using a special kind of escape sequence called an octal escape, but it is preferable to use normal escape sequences where possible. Both normal escape sequences and octal escapes are far preferable to Unicode escapes because unlike Unicode escapes, normal escape sequences and octal escapes are processed after the program is parsed into tokens.
Searches whole web. Use the search in the right sidebar to search only within javajee.com!!!