Lesson 28: Escape Sequences

In past lessons, we have gone over a couple of different ways we can manipulate Strings.  We have learned about various print methods and adding spaces with quotation marks to get our desired output.  In this lesson, we are going to go over escape sequences that can help simplify some of our string manipulation, as well as fix certain issues we run into when printing special symbols.

The term “escape sequences” is derived from the need to “escape” from its normal usage.  For example, say we want to print a String that has quotation marks “”.  However, we know that Java uses quotation marks to begin and end a String.  Let’s look at what happens when we try to make and print a String with quotation marks.

(The code above does not compile or run)

Instead of Java knowing that we want to print quotation marks inside of our String, it does what it is supposed to do – it treats the two sets of quotation marks as two separate Strings.  To escape Java’s standard usage of quotation marks, we use the escape sequence.  In this instance, the escape sequence for quotation marks is \” .  Let’s now try using the escape sequence for quotation marks to fix our code:

By just adding a backslash in front of the quotation marks, we now get the desired outcome:

As we know that there are quite a few different special characters used in Java.  Look at the list below to see some other important escape sequences.

Escape SequenceAction
\tInserts a tab indentation
\nStarts a new line
\rInserts a carriage return (similar to new line)
\bInserts a backspace
\\Allows for the usage of a backslash \ in text
\’Allows for the usage of ‘ in text
\”Allows for the usage of ” in text

Go over the table above to familiarize yourself with the escape sequences listed.  Also know that although carriage return is still used in some cases, we will typically be using \n or using the println() method to start a new line.  In fact, carriage return refers to typewriters and when the carriage had to be manually returned by hand!  Great job and see you next lesson!

GitHub link.

Leave a Reply

%d bloggers like this: