Table of Contents
In this post, we will see how to escape double quotes in String in java.
There are scenarios where you need to escape double quotes
already present in the String. This generally happens while dealing with JSON file format or reading file data.
Escape double quotes in java
Double quotes characters can be escaped with backslash(\
) in java. You can find complete list of String escapes over this java doc.
Let’s understand this with the help of example.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package org.arpit.java2blog; public class EscapeDoubleQuotesStringMain { public static void main(String[] args) { String blogName = "Java2blog is java blog"; System.out.println("BlogName: "+blogName); // Let's put Java2blog in double quotes String blogNameWithDoubleQuotes = "\"Java2blog\" is java blog"; System.out.println("BlogName with double quotes: "+blogNameWithDoubleQuotes); } } |
Output:
BlogName with double quotes: “Java2blog” is java blog
💡 Did you know?
Some IDEs like intelij automatically escape String if you paste the String between double quotes surrounding the String literal.
Add double quotes to String in java
If you want to add double quotes(") to String, then you can use String’s replace() method to replace double quote(") with double quote preceded by backslash(\").
Here is an example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package org.arpit.java2blog; public class AddDoubleQuotesToStringMain { public static void main(String[] args) { String blogName = "Java2blog is java blog"; System.out.println("BlogName: "+blogName); // Let's put Java2blog in double quotes String blogNameWithDoubleQuotes = blogName.replace("Java2blog","\"Java2blog\""); System.out.println("BlogName with double quotes: "+blogNameWithDoubleQuotes); } } |
Output:
BlogName with double quotes: “Java2blog” is java blog
Print String with double quotes in java
If you want to print string with double quotes in java using System.out.println, then you can use either \" or ‘"’ with the String.
Here is an example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package org.arpit.java2blog; public class PrintDoubleQuotesInStringMain { public static void main(String[] args) { String blogName = "Java2blog"; // Using \" System.out.println("\""+blogName+"\""); // Using '"' System.out.println('"'+blogName+'"'); // Using '\u0022' System.out.println('\u0022'+blogName+'\u0022'); } } |
Output:
“Java2blog”
“Java2blog”
That’s all about How to escape double quotes in String in java.