- Create a new file named EscapeSequence.java in your choice of text editor.
- Create a new main method.
- Add the following code to main.
public class EscapeSequence { public static void main(String[] args){ System.out.println("Hello!\nHow are you doing?\n"); }
- Compile and run the program.
$javac EscapeSequence.java $java EscapeSequence Hello! How are you doing?
Note the trailing blank line due to the escaped newline character. For more information on escape sequences, refer to the following Oracle’s The Java Tutorials page.
The escape characters you will use often are the following.
- \t insert a tab
- \n insert a newline
- \’ insert a single quote
- \” insert a double quote
- \\ insert a backslash character
- Open EscapeSequence.java and add the following line to main.
System.out.print("I\'m a \"cool\" programer!\nRight?\n"); System.out.println("Hey\tnow \\ is a backslash");
- Compile and run the program.
$ javac EscapeSequence.java $ java EscapeSequence Hello! How are you doing? I'm a "cool" programer! Right? Hey now \ is a backslash
The complete class should appear as follows.
public class EscapeSequence{ public static void main(String[] args){ System.out.println("Hello!\nHow are you doing?\n"); System.out.print("I\'m a \"cool\" programer!\nRight?\n"); System.out.println("Hey\tnow \\ is a backslash"); } }
If you want more information on print, println, and escape characters, refer to the following short video on YouTube by LearningLad.