Wednesday, January 4, 2023

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 have to be added to the String.

You should have guessed what needed to be done in case you want to display double quotes with in a String 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 );


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();

  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);


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

That's all for this topic 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 in Java
  3. Convert String to Byte Array 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 LinkedList Class Works Internally in Java
  4. Functional Interfaces in Java
  5. Difference Between Checked And Unchecked Exceptions in Java
  6. Synchronization in Java - Synchronized Method And Block
  7. Race Condition in Java Multi-Threading
  8. Java Concurrency Interview Questions And Answers

No comments:

Post a Comment