java

How to escape special characters in Java

In this tutorial, we are going to see how to escape special characters in Java. As you probably know, a string is a sequence of characters. These characters can be letters, numbers, punctuation marks, etc. When creating a string, it must be enclosed in quotes, here is an example:

public class Main {
   public static void main(String[] args) {
       String str = new String("Welcome to StackHowTo!");
   }
}

But what should we do if we have to create a string which itself has to contain quotes?

public class Main {
   public static void main(String[] args) {
       String str = new String("I am using "Microfiber" to clean my house.");
   }
}

Output:

Main.java:3: error: ')' expected
       String str = new String("I am using "Microfiber" to clean my house.");
                                           ^
 
It seems that the compiler is complaining about something!

The compiler interprets quotes in a very specific way, it expects strings to be wrapped in them. And whenever the compiler sees “, it expects the quote to be followed by a second quote, and the content between them to be a string.

To solve this problem, we use the special symbol: \. This symbol is normally referred to as a “backslash”.

Let’s try to change our code:

public class Main {
   public static void main(String[] args) {
       String str = new String("I am using \"Microfiber\" to clean my house.");
	   System.out.println(str);
   }
}

Output:

I am using "Microfiber" to clean my house.

 
 
Let’s look at another example:

public class Main {
   public static void main(String[] args) {
       String dir = new String ("Path C:\Users\doc");
       System.out.println(dir);
   }
}

Output:

Main.java:3: error: illegal escape character
       String dir = new String ("Path C:\Users\doc");
                                         ^
 
Again, the compiler does not understand what to do. The compiler expects the backslash “\” to be followed by a certain character that must be escaped (such as a quotation mark).

But, in this case, “\” is followed by a single letter. The compiler is therefore confused. So what do we have to do? Exactly the same as before, we just add another “\” to our “\”.

public class Main {
   public static void main(String[] args) {
       String dir = new String ("Path C:\\Users\\doc");
       System.out.println(dir);
   }
}

Output:

Path C:\Users\doc
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *