Saturday, March 21, 2020

How to Add Double Quotes to a String - Java Program

You may come across a scenario where you would want to add double quotes to a String, but Java uses double quotes while initializing a String so it won't recognize that double quotes should be added to the String.

You should have guessed what needed to be done in case you want to display double quotes in Java. Yes you need escape character "\" to escape quotes.

So let's see an example.

Displaying double quotes Java example

public class SetQuote {

 public static void main(String[] args) {
    // escaping the double quotes as quotes are
    // needed with in the String
  String value = "\"Ram\"";
  System.out.println("Value - " + value );
 }
}

Output

Value - "Ram"

Let's take another example. You have got a String and you want to enclose part of it in double quotes.

For example let's say you are reading an XML in which first line has no double quotes.

Which means you got it as-

<?xml version=1.0 encoding=UTF-8?>

but it should be

<?xml version="1.0" encoding="UTF-8"?>

That can be done by using replace method of the String and escaping double quotes.

public class SetQuote {
    public static void main(String[] args) {
        SetQuote setQuote = new SetQuote();
        setQuote.replaceQuote();
    }
  
    public void replaceQuote(){
        String xmlString = "<?xml version=1.0 encoding=UTF-8?>";
        xmlString = xmlString.replace("1.0", "\"1.0\"").replace("UTF-8", "\"UTF-8\"");
        System.out.println("xmlString - " + xmlString);
    }
}

Output

xmlString - <?xml version="1.0" encoding="UTF-8"?>

That's all for this topic How to Add Double Quotes to a String - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Count Number of Words in a String - Java Program
  2. If Given String Sub-Sequence of Another String - Java Program
  3. Converting String to Bytearray - Java Program
  4. How to convert date and time between different time-zones in Java
  5. How to sort arraylist of custom objects in Java

You may also like-

  1. How to read file from the last line in Java
  2. Marker interface in Java
  3. How Linked List class works internally in Java
  4. Functional Interfaces in Java
  5. Difference between Checked exception & Unchecked exception
  6. Synchronization in Java multithreading
  7. Race Condition in Java Multi-Threading
  8. Java Concurrency Interview Questions