Hello team!
In this lesson we will learn with you escape sequences in Java.
Let me show you what is escape sequence and how to escape characters.
I believe you already understood that all string literals need to be enclosed in quotation marks.
But what to do in case you need to have string which will contain quotes in itself?
In this example I want to put book name in quotes.
To do this, I need to use character escaping by using a special symbol backslash.
I can escape quotation marks.
In Java, a backslash combined with a character to be escaped is called an escape sequence.
In case I don't use backslash in this example, there will be compilation error.
Java compiler is very smart program, but it will be hard for it to compile string in such format.
Java compiler expects that each string is started with quote and ended with quote.
That's why without escape sequence for Java compiler, it will be impossible to understand that you
want to have this string as part of the whole string.
Let's consider another example.
You want to have string which will contain directory path on your computer and you need to use backslash.
But Java compiler knows that in source code will use backslash only in case we want to create escape
sequence, and in this case compiler simply cannot find escape sequence because you don't need to escape
J character.
That's why you need to escape your backslash character.
And we have here double backslash in the source code but single backslash in the output.
In Java there are limited amount of escape sequences.
Here you can find all lists of escape sequences for example backslash and t inserts, tab character
backslash and n inserts newline character.
Here is an example with two lines in one string object.
You see backslash and n here.
And here is the output.
Here is one line and the second line.
I encourage you to try these escape sequences in your source code.
Another important thing to know about escaping characters in Java Unicode table includes the symbols
of almost every written language in the world.
In case you need to use Unicode character in your string, you can just escape Unicode code.
All Unicode characters codes have the form U plus hexadecimal number.
So if you need to use character from Unicode table, just escape this value and you will see copyright
character in the output.
That's all.
Thank you for your attention and see you in the next lesson.