Escape Double Quotes in Java String

There are some cases when we need to have double quotes as part of the String. In this post, you will see how to escape double quotes in Java String using the escape character (/).

Escaping double quotes in Java String

If we try to add double quotes inside a String, we will get a compile-time error. To avoid this, we just need to add a backslash (/) before the double quote character.

In this example, we want to print double quotes around the words “Steve” and “Java”.

class EscapeDoubleQuotesInString {

  public static void main(String[] args) {

    String str = "Hello, I'm \"Steve\" and I am \"Java\" developer";

    System.out.println(str);

  }
}
Output: Hello, I’m “Steve” and I am “Java” developer

Escape double quotes in a JSON object in Java

There are many cases where you might need to escape double quotes. In this example, you will learn how to escape double quotes in JSON objects.

You can learn more about JSON objects in this tutorial Java JSON tutorial

import org.json.JSONObject;

public class EscapeJson {
    public static void main(String[] args) {
        String jsonString = "{\"name\":\"John Doe\",\"age\":\"30\",\"address\":\"\"\"New York\"\"\"}";
        JSONObject jsonObject = new JSONObject(jsonString);
        System.out.println(jsonObject);
    }
}

In this example, we create a JSON object using the JSONObject class from the org.json library. The string that we pass to the JSONObject constructor contains double quotes that need to be escaped. We are doing this by placing a backslash (/) before each double quote that we want to escape. We can then use the jsonObject as a normal JSON object and can access the properties as well.

Leave a Reply

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