Core JavaJava Basics

Java Escape characters list

In this post, we feature a comprehensive article about escaping characters in Java. Why do we use Java Escape characters list so-called Sequence character?

1. Introduction

Consider an example where I want to print the following message: My favorite movie is “Avengers”

Let’s try to write the code to print this string.

MyFavoriteMovieExample .java

public class MyFavoriteMovieExample {
 public static void main(String[] args) {
 String myFavoriteMovie = new String("My favorite movie is "Avengers".");
 System.out.println(myFavoriteMovie);
 }
}

The compiler doesn’t let us run this code and It shows us syntax error. The reason is, it is unable to interpret the Double Quote " correctly. Usually for compiler " specify either the start or end of the string but what if we want it to be a part of a string, we must need something to differentiate " symbol to interpret differently in some scenario. There escape character comes into the picture. By prefixing backslash \ before the ",the compiler treats the symbol as a part of the string and not start or end of the string.

Let’s fix the error here.

MyFavoriteMovieExample .java

1
2
3
4
5
6
public class MyFavoriteMovieExample {
  public static void main(String[] args) {
    String myFavoriteMovie = new String("My favorite movie is \"Avengers\".");
    System.out.println(myFavoriteMovie);
  }
}

Output

1
My favorite movie is "Avengers".

After executing this code our desired string is printed on the console.

Although there is an alternate way to get the same output but it doesn’t mean we can write alternative for all the other special characters.

Here is an example to get the same output without using escape character.

MyFavoriteMovieExample .java

public class MyFavoriteMovieExample{
	public static void main(String[] args) {
		String myFavoriteMovie = "My favorite movie is " + '"' + "Avengers" + '"' + ".";
		System.out.println(myFavoriteMovie);
	}
}

It will give us the same output.

2. Different types of escape characters

  • \f : for inserting a formfeed.
  • \' : for inserting a quote character.
  • \" : for inserting a double quote character.
  • \\ : for inserting a backslash character.
  • \t : for inserting a tab.
  • \b : for inserting a backspace.
  • \n : for inserting a newline.
  • \r : for inserting a carriage return.

let’s see the use case for each escape character:

EscapeCharacterExample.java

public class EscapeCharacterExample {

	public static void main(String[] args) {
		// \t tab
		printEscapeCharacterWithExample("tab : \\t", '\t');
		// \b backspace
		printEscapeCharacterWithExample("backspace : \\b", '\b');
		// \n new line
		printEscapeCharacterWithExample("new line  : \\n", '\n');
		// \r carriage return
		printEscapeCharacterWithExample("carriage return : \\r", '\r');
		// \f form feed
		printEscapeCharacterWithExample("form feed : \\f", '\f');
		// \' single quote
		printEscapeCharacterWithExample("single qoute : \\'", '\'');
		// \" double quote
		printEscapeCharacterWithExample("double quote : \"", '\"');
		// \\ backslash
		printEscapeCharacterWithExample("backslash : \\", '\\');
	}

	static void printEscapeCharacterWithExample(String escapeCharacterString, char escapeCharacter) {
		String preText = "Pre Text";
		String middleText = "Middle Text";
		String postText = "Post Text";
		System.out.println(escapeCharacterString);
		System.out.println(preText + escapeCharacter + middleText + escapeCharacter + postText);
		System.out.println();
	}
}

Output

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
tab : \t                                                                                                               
Pre Text        Middle Text     Post Text                                                                              
                                                                                                                         
backspace : \b                                                                                                         
Pre TexMiddle TexPost Text                                                                                             
                                                                                                                         
new line  : \n                                                                                                         
Pre Text                                                                                                               
Middle Text                                                                                                            
Post Text                                                                                                              
                                                                                                                         
carriage return : \r                                                                                                   
Post Textxt                                                                                                            
                                                                                                                         
form feed : \f                                                                                                         
Pre Text                                                                                                               
        Middle Text                                                                                                    
                   Post Text                                                                                           
                                                                                                                         
single qoute : \'                                                                                                      
Pre Text'Middle Text'Post Text                                                                                         
                                                                                                                         
double quote : "                                                                                                       
Pre Text"Middle Text"Post Text                                                                                         
                                                                                                                         
backslash : \                                                                                                          
Pre Text\Middle Text\Post Text

3. Unicode Escape Characters

Java support Unicode escape characters which are basically the representation of almost all the different language characters using only ASCII characters.

A Unicode escape representation consist of a backslash character / followed by one or more u characters and four hexadecimal digits. While interpreting the string if compiler finds something in the Unicode representation, compiler replace it with respective symbol according to the Java specification .

UnicodeExample.java

1
2
3
4
5
6
7
public class UnicodeExample {
 
  public static void main(String[] args) {
    System.out.println("\u0929\u092E\u0938\u094D\u0924\u0947");
  }
 
}

Output

1
ऩमस्ते

The above program will print ऩमस्ते which is a Hindi word and we can’t write those symbols with a normal qwerty keyboard so we require Unicode characters to represent those symbols.

This was an article about escaping characters in Java.

4. Download the source code

Download
You can download the source code of this example here: Java Escape characters list

Yusuf Ansari

I am Yusuf Ansari, I earned my degree in Information Technology from Guru Gobind Singh Indraprastha University. I have over two years of professional experience in Java based application development.I have worked as a backend developer mostly but also worked on the front-end part in some React.js based projects.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button