Built-in Types: Escape Sequences

Escape Characters

Suppose you want to print a message with quotation marks in the output. Can you write a statement like this?

System.out.println(“He said “Java is fun””);

No, this statement has a compile error. The compiler thinks the second quotation character is the end of the string and does not know what to do with the rest of the characters.

To overcome this problem, Java uses a special notation to represent special characters, as shown in Table 2.6. This special notation, called an escape character, consists of a backslash (\) followed by a character or a character sequence. For example, \t is an escape character for the Tab character and an escape character such as \u03b1 is used to represent a Unicode. The symbols in an escape character are interpreted as a whole rather than individually.

So, now you can print the quoted message using the following statement:

System.out.println(“He said \”Java is fun\””); The output is
He said “Java is fun”
Note that the symbols \ and together represent one character.

Escape Characters

Copy and paste this table to your JavaIntroNotes_YI document

https://docs.oracle.com/javase/tutorial/java/data/characters.html

  • Write a program NamePrinter_YI that displays your name inside a box, like this:

Do your best to approximate lines with characters, such as |, -, and +.

  • Write a program FacePrinter_YI that prints a face, using text characters, hopefully, better looking than this one:
  • (Optional)Write a program CatPrinter_YI that prints an animal speaking a greeting, similar to (but different from) the following